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 a ParamType that overrides shell_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 via CarapaceComplete.

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 appends parts to it. An unset or empty variable falls back to fallback, the full default path the XDG spec derives from that variable’s own default base, which already carries the parts. A leading ~ is expanded against the HOME in 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. Pass fallback in its ~ form for that: a path expanded at import carries that HOME for good.

Return type:

Path

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_HOME asks every tool to keep its cache there, macOS included. Unlike xdg_dir(), a relative value is ignored, as the XDG specification says: a cache must not move with the working directory.

Return type:

Path

class click_extra.carapace.CarapaceCompletion(flag=dict(), positional=list(), positionalany=list())[source]

Bases: object

The completion block of a command: per-flag and positional actions.

flag: dict[str, list[str]]

Map of flag name (long spelling, no dashes) to its completion action.

positional: list[list[str]]

Per-position completion actions for fixed-arity arguments, in order.

positionalany: list[str]

Completion action repeated for every trailing variadic argument.

to_dict()[source]

Serialize to the carapace-spec completion mapping, dropping empty members and trailing empty positional slots.

Return type:

dict

class click_extra.carapace.CarapaceDocumentation(positional=list(), positionalany='')[source]

Bases: object

The documentation block 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.positional holds actions, not text. This block is where the upstream schema puts that prose, indexed the same way, so carapace --style and 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, dash and dashany: the first two would restate what description and flags already say, and Click has no ---separated argument family to feed the last two.

positional: list[str]

Per-position help text for fixed-arity arguments, in order.

positionalany: str = ''

Help text for the trailing variadic argument.

to_dict()[source]

Serialize to the carapace-spec documentation mapping.

Drops empty members and trailing undocumented slots, keeping the surviving ones index-aligned with completion.positional.

Return type:

dict

class click_extra.carapace.CarapaceCommand(name, description='', aliases=(), hidden=False, flags=dict(), persistentflags=dict(), exclusiveflags=list(), completion=CarapaceCompletion(), documentation=CarapaceDocumentation(), commands=list())[source]

Bases: object

One node of a Carapace spec: a command and its flags, completions and subcommands, mirroring the upstream Command schema.

name: str

The command’s invocation name (the root carries the program name).

description: str = ''

One-line command description (NAME-section short help).

aliases: tuple[str, ...] = ()

Alternative names the command also answers to (from Cloup).

hidden: bool = False

Whether the command is hidden from listings (still completable).

flags: dict[str, str]

Map of flag key (with shape suffixes) to its description.

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.

exclusiveflags: list[list[str]]

Groups of mutually-exclusive flag names (from Cloup constraints).

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.

to_dict()[source]

Serialize to a carapace-spec command mapping, dropping empties.

Only name is required by the schema, so every other member is omitted when empty to keep the YAML compact.

Return type:

dict

click_extra.carapace.extract_carapace_command(command, ctx, *, command_path)[source]

Build a CarapaceCommand from a Click command and its context.

The context must have been created for command (typically via click.Command.make_context() with resilient_parsing=True). Subcommands are discovered dynamically and recursed into.

Every option lands in the flags of 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. Carapace persistentflags would offer it after the subcommand too, where Click rejects it.

command_path is 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:

CarapaceCommand

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 ctx when given (the live invocation context), otherwise builds a throwaway one with resilient_parsing=True. The returned mapping conforms to the carapace-spec schema and is ready to hand to yaml.safe_dump.

Return type:

dict

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, the invocation command line that produced it (when given), and a link to the documentation.

Return type:

str

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. invocation is recorded in the header comment (see dump_carapace_spec()).

Return type:

Path

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>.yaml when that variable is set, else ~/.config/carapace/specs/<prog>.yaml, both resolved at call time by xdg_dir(): Carapace loads either on startup. Returns the path.

Return type:

Path

class click_extra.carapace.CarapaceComplete(cli, ctx_args, prog_name, complete_var)[source]

Bases: ShellComplete

Click completion backend that emits Carapace’s value/description lines.

Registered as the carapace shell, so _FOO_COMPLETE=carapace_complete makes a Click CLI print completions in the value\tdescription text format Carapace’s shell macro parses. This is the callback target of the dynamic actions emitted by _dynamic_action(); it reuses Click’s own get_completions(), so a parameter’s custom shell_complete is 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_complete completion instruction).

source_template: ClassVar[str] = ''

Completion script template formatted by source(). This must be provided by subclasses.

source()[source]

No-op source step: Carapace, not a shell, consumes this backend.

Return type:

str

get_completion_args()[source]

Read the words Carapace passed via COMP_WORDS (program name first).

Returns the typed arguments with an empty incomplete value: Carapace applies its own prefix filtering to the candidates returned.

Return type:

tuple[list[str], str]

format_completion(item)[source]

Render one completion as Carapace’s value or value\tdescription.

Return type:

str