API Reference#
Auto-Completion#
Configuration and Utilities for auto-completion in the REPL.
- class click_repl.completer.ClickCompleter(group_ctx: Context, internal_commands_system: InternalCommandSystem, bottom_bar: AnyFormattedText | BottomBar = None, shortest_option_names_only: bool = False, show_only_unused_options: bool = False, show_hidden_commands: bool = False, show_hidden_params: bool = False)[source]#
Custom prompt completion provider for the click-repl app.
- Parameters:
group_ctx – The click context object of the main group.
bottom_bar – Object that’s used to update the text displayed in the bottom bar. If not required, it should be explicitly set to
None.internal_commands_system – Object that holds the information about the internal commands and their prefixes.
shortest_option_names_only –
Determines whether only the shortest name of an option parameter should be used for auto-completion.
It is utilized when the user is requesting option flags without providing any text. They are not considered for option flags.
show_only_unused_options – Determines whether the options that are already mentioned or used in the current prompt will be displayed during auto-completion.
show_hidden_commands – Determines whether hidden commands should be shown in auto-completion or not.
show_hidden_params – Determines whether hidden parameters should be shown in auto-completion or not.
- check_for_command_arguments_request(ctx: Context, state: ReplInputState, incomplete: Incomplete) bool[source]#
Determines whether the user has requested auto-completions for the given command’s parameters.
- Parameters:
ctx – The current click context object.
state – Object that contains information about the input state of the parameters of the current command.
incomplete – Object that contains the unfinished string in the REPL prompt, and its parsed state, that requires further input or completion.
- Returns:
bool–Trueif auto-completions should be generated for the parameters of the given command,Falseotherwise.
- get_completion_for_boolean_type(param: Parameter, incomplete: Incomplete) Generator[Completion, None, None][source]#
Generates auto-completions for
BOOLtype parameter based on the givenparam.- Parameters:
param – The parameter for which auto-completions are generated.
incomplete – Object that contains the incomplete string in the REPL prompt.
- Yields:
prompt_toolkit.completion.Completion– Completion objects for auto-completing boolean types.
- get_completion_for_command_arguments(ctx: Context, command: Command, state: ReplInputState, incomplete: Incomplete) Generator[Completion, None, None][source]#
Generates auto-completions to display the flags of the options based on the given command object.
- Parameters:
ctx – The current click context object.
command – A click command object for which auto-completions are generated based on its parameters.
state – Object that contains information about the input state of the parameters of the current command.
incomplete – Object that contains the incomplete string in the REPL prompt.
- Yields:
prompt_toolkit.completion.Completion– Completion objects for auto-completing the current command’s arguments.
- get_completion_for_option_flags(ctx: Context, command: Command, state: ReplInputState, incomplete: Incomplete) Generator[Completion, None, None][source]#
Generates auto-completions for option flags based on the given command.
- Parameters:
ctx – The current click context object.
command – A click command object, which is referred to generate auto-completions based on its parameters.
state – Object that contains information about the input state of the parameters of the current command.
incomplete – Object that contains the incomplete string in the REPL prompt.
- Yields:
prompt_toolkit.completion.Completion– Completion objects for auto-completing the given flag-type option.
- get_completion_for_path_types(param: Parameter, param_type: click.Path | click.File, incomplete: Incomplete) Generator[Completion, None, None][source]#
Generates auto-completions for
PathandFiletype parameters.- Parameters:
param – The parameter for which auto-completions are generated.
param_type – The Path or File ParamType object of the
param.incomplete – Object that contains the incomplete string in the REPL prompt.
- Yields:
prompt_toolkit.completion.Completion– Completion objects for auto-completing click path types.
- get_completion_from_autocompletion_functions(ctx: Context, param: Parameter, state: ReplInputState, incomplete: Incomplete, param_type: ParamType | None = None) Generator[Completion, None, None][source]#
Generates auto-completions based on the output from the command’s
shell_complete()orautocompletionfunction of theparam.- Parameters:
ctx – The current click context object.
param – The parameter for which auto-completions are generated.
state – Object that contains information about the input state of the current parameter.
incomplete – Object that contains the incomplete string in the REPL prompt.
param_type – The ParamType object of a parameter, to which the auto-completions are generated from their
shell_complete()methods.
- Yields:
prompt_toolkit.completion.Completion– Completion objects for auto-completion for the given parameter and/or its type.
- get_completion_from_choices_type(param: Parameter, param_type: click.Choice, incomplete: Incomplete) Generator[Completion, None, None][source]#
Generates auto-completions based on data from the given
Choiceparameter type of aparam.This method is used for backwards compatibility with click v7 as
Choiceclass didn’t have ashell_complete()method until click v8.- Parameters:
param – The parameter for which auto-completions are generated.
param_type – The Choice ParamType object of
param, to which the auto-completions are generated.incomplete – Object that contains the incomplete string in the REPL prompt.
- Yields:
prompt_toolkit.completion.Completion– Completion objects for auto-completions for the choices type.
- get_completion_from_param(ctx: Context, param: Parameter, state: ReplInputState, incomplete: Incomplete) Generator[Completion, None, None][source]#
Generates auto-completions based on the given
param.- Parameters:
ctx – The current click context object.
param – The parameter for which auto-completions are generated.
state – Object that contains information about the input state of the parameters of the current command.
incomplete – Object that contains the incomplete string in the REPL prompt.
- Yields:
prompt_toolkit.completion.Completion– Completion objects for auto-completing the given parameter.
- get_completion_from_param_type(ctx: Context, param: Parameter, param_type: ParamType, state: ReplInputState, incomplete: Incomplete) Generator[Completion, None, None][source]#
Generates auto-completions based on the given
param_typeobject of the givenparam.- Parameters:
ctx – The current click context object.
param – The parameter for which auto-completions are generated.
param_type – The ParamType object of
param, defining the type of value to be generated.state – Object that contains information about the input state of the parameters of the current command.
incomplete – Object that contains the incomplete string in the REPL prompt.
- Yields:
prompt_toolkit.completion.Completion– Completion objects for auto-completing the ParamType of the current parameter.
- get_completions(document: Document, complete_event: CompleteEvent | None = None) Generator[Completion, None, None][source]#
Provides
Completionobjects from the obtained current input string in the REPL prompt.- Parameters:
document – The Document object containing the text that’s currently in the REPL.
complete_event – The CompleteEvent object of the current prompt.
- Yields:
prompt_toolkit.completion.Completion– Completion objects for command line auto-completion.
- get_completions_for_internal_commands(prefix: str, incomplete: str) Generator[Completion, None, None][source]#
Generates auto-completions based on the given prefix present in the current incomplete prompt.
- Parameters:
prefix – The prefix string thats present in the start of the prompt.
incomplete – Object that contains the incomplete string in the REPL prompt.
- Yields:
prompt_toolkit.completion.Completion– Completion objects for auto-completing internal commands.
- get_completions_for_joined_boolean_option_flags(ctx: Context, option: click.Option, state: ReplInputState, incomplete: Incomplete) Generator[Completion, None, None][source]#
Generates auto-completions for boolean option flags, to display all their names joined together in a single command-line sugestion, if
shortest_option_names_onlyis set toTrue.It also generates coloured option flags, only if there are any exclusive flags to pass in the “
False’y” value of the specifiedoption.- Parameters:
ctx – The current click context object.
option – A click option object which is referred to generate auto-completions for its flags
state – Object that contains information about the input state of the parameters of the current command.
incomplete – Object that contains the unfinished string in the REPL prompt
- Yields:
prompt_toolkit.completion.Completion– Completion objects for auto-completing the given boolean flag option.
- get_completions_for_subcommands(ctx: Context, state: ReplInputState, incomplete: Incomplete) Generator[Completion, None, None][source]#
Provides auto-completions for command names, based on the current command and group.
- Parameters:
ctx – The current click context object.
state – Object that contains information about the input state of the parameters of the current command.
incomplete – Object that contains the incomplete string in the REPL prompt.
- Yields:
prompt_toolkit.completion.Completion– Completion objects to auto-complete sub-command names of the current group.
- get_multicommand_for_generating_subcommand_completions(ctx: Context, state: ReplInputState, incomplete: Incomplete) MultiCommand | None[source]#
Returns the appropriate
MultiCommandobject that should be used to generate auto-completions for suggesting subcommands of a group.- Parameters:
ctx – The current click context object.
state – Object that contains information about the input state of the parameters of the current command.
incomplete – Object that contains the incomplete string in the REPL prompt.
- Returns:
MultiCommand | None– A click multiCommand object, if available, which is supposed to be used for generating auto-completion for suggesting its subcommands.
- get_visible_subcommands(ctx: Context, multicommand: MultiCommand, incomplete: str) Generator[Command, None, None][source]#
Get all the subcommands from the given
multicommandwhose name starts with the givenincompleteprefix string.- Parameters:
ctx – The current click context object.
multicommand – A click multicommand object, which is used for generating auto-completion for suggesting its subcommands.
incomplete – Object that contains the incomplete string in the REPL prompt.
- Yields:
click.Command– Click command type sub-command objects of themulticommandobject.
- handle_internal_commands_request(document_text: str) Generator[Completion, None, bool][source]#
Handles internal commands request from the REPL, by suggesting auto-completions for the incomplete internal command request, and clearing the bottom bar, if exists.
- Parameters:
document_text – The text currently in the REPL prompt.
- Returns:
bool–Trueif there’s an internal command request from the REPL,Falseotherwise.- Yields:
prompt_toolkit.completion.Completion– Completion objects for auto-completing internal commands.
- bottom_bar[source]#
Object that’s used to update the text displayed in the bottom bar. If not required, it should be explicitly set to
None.
- parent_token_class_name: str[source]#
Parent class name for tokens that are related to
ClickCompleter.
- shortest_option_names_only[source]#
Determines whether only the shortest name of an option parameter should be used for auto-completion.
Determines whether the hidden commands should be shown in auto-completion or not.
Determines whether the hidden parameters should be shown in auto-completion or not.
- class click_repl.completer.ReplCompletion(text: str, incomplete: Incomplete | str, *args: Any, **kwargs: Any)[source]#
Custom Completion class for generating
Completionobjects with the default settings for proper auto-completion in the REPL prompt.- Parameters:
text – The string that should fill in the prompt during auto-completion.
incomplete – The incomplete string in the prompt. It’s used to get the
start_positionfor the Completion to swap text with.*args – Additional arbitrary arguments for the
Completionclass.**kwargs – Additional keyword arguments for the
Completionclass.
Context#
Core functionalities for managing context of the click_repl app.
- class click_repl.core.ReplContext(group_ctx: Context, internal_command_system: InternalCommandSystem, bottombar: AnyFormattedText | BottomBar = None, prompt_kwargs: dict[str, Any] = {}, parent: ReplContext | None = None)[source]#
Context object for the REPL sessions.
This class tracks the depth of nested REPLs, ensuring seamless navigation between different levels. It facilitates nested REPL scenarios, allowing multiple levels of interactive REPL sessions.
Each REPL’s properties are stored inside this context class, allowing them to be accessed and shared with their parent REPL.
All the settings for each REPL session persist until the session is terminated.
- Parameters:
group_ctx – The click context object that belong to the CLI/parent Group.
internal_command_system – Holds information about the internal commands and their prefixes.
bottom_bar –
Text or callable returning text, that should be displayed in the bottom toolbar of the
PromptSessionobject.Alternatively, it can be a
BottomBarobject to dynamically adjust the command description displayed in the bottom bar based on the user’s current input state.prompt_kwargs – Extra keyword arguments for
PromptSessionclass.parent – REPL Context object of the parent REPL session, if exists. Otherwise,
None.
- history() Generator[str, None, None][source]#
Generates the history of past executed commands.
- Yields:
str– The executed command string from the history, in chronological order from most recent to oldest.
- session_reset() None[source]#
Resets values of
PromptSessionto the providedprompt_kwargs, discarding any changes done to thePromptSessionobject.
- to_info_dict() ReplContextInfoDict[source]#
Provides a dictionary with minimal info about the current REPL.
- Returns:
ReplContextInfoDict– A dictionary that has the instance variables and their values.
- update_state(state: ReplInputState) None[source]#
Updates the current input state of the REPL in itself, and in
bottom_bar.- Parameters:
state – A ReplInputState object that keeps track of the current input state.
- bottom_bar[source]#
Text or callable returning text, that should be displayed in the bottom toolbar of the
PromptSessionobject.Alternatively, it can be a
BottomBarobject to dynamically adjust the command description displayed in the bottom bar based on the user’s current input state.
- current_state: ReplInputState | None[source]#
Current input state of the commands and their parameters in the REPL.
- parent: Final[ReplContext | None][source]#
REPL Context object of the parent REPL session, if exists. Otherwise,
None.
- prompt_kwargs[source]#
Extra keyword arguments for
PromptSessionclass.
- click_repl.core.pass_context(func: Callable[[Concatenate[ReplContext, P]], R]) Callable[[P], R][source]#
Decorator that marks a callback function to receive the current REPL context object as its first argument.
- Parameters:
func – The callback function to pass context as its first parameter.
- Returns:
Callable[P,R]– The decorated callback function that receives the current REPL context object as its first argument.
Internal Commmands#
Utilities to manage the REPL’s internal commands.
- class click_repl.internal_commands.InternalCommandSystem(internal_command_prefix: str | None = ':', system_command_prefix: str | None = '!')[source]#
Utility for managing and executing internal/system commands from the REPL. Commands are triggered by their respective prefixes.
- Parameters:
internal_command_prefix – Prefix to trigger internal commands.
system_command_prefix – Prefix to execute command-line scripts.
- Raises:
click_repl.exceptions.SamePrefix – If both
internal_command_prefixandsystem_command_prefixare same.
Note
The prefixes determine how the commands are recognized and distinguished within the REPL.
Both the
internal_command_prefixandsystem_command_prefixshould not be the same.- dispatch_system_commands(command: str) None[source]#
Execute system commands entered in the REPL. System commands start with the
system_command_prefixstring in the REPL.- Parameters:
command – Contains the system command that needs to be executed.
- execute(string: str) None[source]#
Executes incoming Internal and System commands.
- Parameters:
string – Input string that has to be parsed and executed.
- Raises:
PrefixNotFound – If there is no internal prefix used in the given command.
- get_command(name: str, default: ~click_repl.internal_commands.T = <object object>) Callable[[], None] | T[source]#
Retrieves the callback function of the internal command if available.
- Parameters:
name – The name of the desired internal command.
default – The sentinel value that has to be returned if the internal command with the given name is not found.
- Returns:
Callable[[],None] | T– The callback function of the internal command, if found. Otherwise, it returns the value specified in thedefaultparameter.
- get_prefix(command: str) tuple[str, str | None][source]#
Extracts the prefix from the beginning of the
commandstring.- Parameters:
command – Input string that needs to be parsed.
- Returns:
tuple[str,str | None]– A tuple containing: - The type of the prefix. - The prefix found at the beginning of the command string.Noneif its not known.
- handle_internal_commands(command: str) None[source]#
Run REPL-internal commands that start with the
internal_command_prefixstring in the REPL.- Parameters:
command – Contains the internal command that needs to be to be executed.
- list_commands() list[list[str]][source]#
List of internal commands that are available.
- Returns:
list[list[str]]– Contains all the names and aliases of each available internal command.
- register_command(target: Callable[[], None] | None = None, *, names: str | Sequence[str] | Generator[str, None, None] | Iterator[str] | None = None, description: str | None = None) Callable[[Callable[[], None]], Callable[[], None]] | Callable[[], None][source]#
Decorator used to register a new internal command from the given function.
Internal commands are case-insensitive, and this decorator allows for easy registration of command names and aliases.
- Parameters:
target – The callback function for the internal command.
names – Names and aliases for the internal command.
description – Help text for the internal command.
- Returns:
Callable[[Callable[[],None]],Callable[[],None]] | Callable[[],None]– The same function object passed into this decorator, or a function that takes and returns the same function when called.
- remove_command(name: str, remove_all_aliases: bool = True) None[source]#
Removes the internal command with the given name, if it exists.
- Parameters:
name – The name of the internal command to be removed.
remove_all_aliases – Determines whether to remove all aliases associated with the command.
- Raises:
InternalCommandNotFound – If there’s no such internal command with the specific
name.
- validate_prefix(prefix: str | None, var_name: str) None[source]#
Raises an error if the given
prefixis not in the expected format.- Parameters:
prefix – The prefix to be checked.
var_name – The name of the variable passed to the
prefixargument.
- Raises:
click_repl.exceptions.WrongType – If the prefix is not of type
strorNone.ValueError – If the prefix is an empty string.
- property internal_command_prefix: str | None[source]#
Prefix to trigger internal commands.
- Returns:
str | None– The prefix for internal commands, if available.- Raises:
click_repl.exceptions.WrongType – If the value being assigned is not of type
str.click_repl.exceptions.SamePrefix – If the new prefix thats being assigned is the same as the current prefix.
- property system_command_prefix: str | None[source]#
Prefix to execute system commands.
- Returns:
str | None– The prefix for system commands, if available.- Raises:
click_repl.exceptions.WrongType – If the value being assigned is not of type
str.click_repl.exceptions.SamePrefix – If the new prefix thats being assigned is the same as the current prefix.
Validation#
Core utilities for input validation and displaying error messages raised during auto-completion.
- class click_repl.validator.ClickValidator(group_ctx: Context, internal_commands_system: InternalCommandSystem, display_all_errors: bool = True)[source]#
Custom prompt input validation for the REPL.
- Parameters:
group_ctx – The current click context object.
internal_commands_system – Holds information about the internal commands and their prefixes.
display_all_errors – Determines whether to raise generic python exceptions, and not display them in the validator bar, resulting in the full error traceback being redirected to a log file.
- validate(document: Document) None[source]#
Validates the input from the prompt.
Any errors raised while parsing text in prompt are displayed in the validator bar.
- Parameters:
document – The incomplete string from the REPL prompt.
- Raises:
prompt_toolkit.validation.ValidationError – If there’s any error occurred during input validation, and needs to be displayed in the validator bar.
Exception – If there’s error that needs to be raised normally.
Bottom Bar#
Utility for the Bottom bar of the REPL.
- class click_repl.bottom_bar.BottomBar(show_hidden_params: bool = False)[source]#
Manage the text displayed in the bottom bar.
- Parameters:
show_hidden_params – Determines whether to display hidden params at bottom bar.
- display_exception(exc: Exception) None[source]#
Displays the provided exception, which was raised during auto-completion generation, in the bottom bar. The exception appears as text with a red background, replacing the display of the metavar description for the current group or the current command’s arguments.
Parameter#
- exc
The exception that should be displayed in the bottom bar.
- format_metavar_tokens_for_param_with_nargs(param: Parameter, param_info: ParamInfo) ListOfTokens[source]#
Constructs the final tokens list to describe the given
param, incorporating information from the providedparam_infodictionary.- Parameters:
param – The parameter to be described.
param_info – A dictionary that has tokens lists that describe about the given parameter.
- Returns:
ListOfTokens– Tokens that describe the givenparam, including appropriate metavar templates and formatting.
- get_formatted_text() ListOfTokens[source]#
Retrieves the next chunk of text to be displayed in the bottom bar, sliced from the
textobject.- Returns:
ListOfTokens– The next chunk of text to be displayed in bottom bar.
- get_group_metavar_template() Marquee[source]#
Gets the metavar to describe the CLI Group, indicating whether it is a
Groupor aCommand.
- get_param_info_tokens(param: Parameter) ListOfTokens[source]#
Constructs the final tokens list to describe the given
param. This method constructs theparam_infodictionary internally and passes it along to other methods to feed in the description about theparam.- Parameters:
param – The parameter to be described.
param_info – A dictionary that has tokens lists that describe about the given parameter.
- Returns:
ListOfTokens– Tokens that describe the givenparamwith appropriate metavar templates and formatting.
- get_param_name_token(param: Parameter) Token[source]#
Returns the token representing the name of the given
param, based on its type.- Parameters:
param – The click parameter for which to determine its name token.
- Returns:
Token– Token that represents the givenparam’s name.
- get_param_nargs_info_tokens(param: Parameter, param_info: ParamInfo) ListOfTokens[source]#
Constructs tokens list to describe the
nargsinformation of the givenparam.- Parameters:
param – The parameter for which its nargs information must be described.
param_info – A dictionary that has tokens lists that describe about the given parameter.
- Returns:
ListOfTokens– Tokens that describe the nargs information of the givenparamwith proper metavar content.
- get_param_tuple_type_info_tokens(param: Parameter) ListOfTokens[source]#
Constructs tokens list to describe the given
param’sTupletype.- Parameters:
param – The click parameter for which its types in
Tupleneeds to be described.- Returns:
ListOfTokens– Tokens that describe the givenparam’s type.
- get_param_type_info_tokens(param: Parameter, param_type: ParamType) ListOfTokens[source]#
Constructs tokens list to describe the
param_typeof the givenparam.- Parameters:
param – The parameter for which its type must be described.
param_type – The ParamType of the given
param. This can be an individual ParamType object from the list inTuple.
- Returns:
ListOfTokens– Tokens that describe the type of the givenparam, based on the specifiedparam_type.
- get_param_usage_state_token(param: Parameter) str[source]#
Returns a token class name that describes the usage state of a parameter in the context of a REPL.
- Parameters:
param – The click parameter for which to determine its usage state.
- Returns:
str– A string describing the givenparam’s usage state.
- make_formatted_text() Marquee[source]#
Constructs a Marquee object containing tokens to describe the current REPL input state of the prompt.
- Returns:
click_repl.tokenizer.Marquee– Marquee object that needs to be displayed to show the updated information about the current REPL input state.
- reset_state() None[source]#
Resets the current input state object and clears the content in the bottom bar.
- update_state(state: ReplInputState) None[source]#
Updates the current input state object in the
BottomBar.- Parameters:
state – Current input state of the prompt.
Determines whether to display hidden params at bottom bar
- state: ReplInputState | None[source]#
Current REPL input state object.
Repl#
Core functionality of the REPL.
- class click_repl._repl.Repl(ctx: Context, prompt_kwargs: dict[str, Any] = {}, completer_cls: type[Completer] = <object object>, validator_cls: type[Validator] | None = <object object>, completer_kwargs: dict[str, Any] = {}, validator_kwargs: dict[str, Any] = {}, internal_command_prefix: str | None = ':', system_command_prefix: str | None = '!')[source]#
Executes the REPL with proper necessary arrangements.
- Parameters:
ctx – The root/parent/CLI group’s context object.
prompt_kwargs – Keyword arguments passed to the
PromptSessionclass.completer_cls – Completer type class to generate
ClickCompleterclass is used by default.validator_cls – Validator class to display error messages in the validator bar during input validation.
ClickValidatorclass is used by default.completer_kwargs – Keyword arguments passed to the constructor of
completer_clsclass.validator_kwargs – Keyword arguments passed to the constructor of
validator_clsclass.internal_command_prefix – Prefix that triggers internal commands within the REPL.
system_command_prefix – Prefix that triggers system commands within the REPL.
Note
You don’t have to pass the
CompleterandValidatorobjects viaprompt_kwargs. But if its still done, then the REPL uses the completer and validator from it.- execute_click_command(command: str | Sequence[str]) None[source]#
Executes click command received from the REPL.
- Parameters:
command – The command string to be parsed and executed.
- execute_command(command: str) None[source]#
Executes commands received from the REPL.
- Parameters:
command – The command string to be parsed and executed.
- get_command() str[source]#
Retrieves input for the REPL.
- Returns:
str– Input text from REPL prompt.
- get_default_completer_kwargs(completer_cls: type[Completer] | None, completer_kwargs: dict[str, Any]) dict[str, Any][source]#
Generates default keyword arguments for initializing a
Completerobject, either using default values or user-defined values, if available.- Parameters:
completer_cls – A completer class.
completer_kwargs – Keyword arguments passed to the
completer_clsclass.
- Returns:
dict[str,Any]– Keyword arguments that should be passed to theCompleterclass.
- get_default_prompt_kwargs(completer_cls: type[Completer], completer_kwargs: dict[str, Any], validator_cls: type[Validator] | None, validator_kwargs: dict[str, Any], prompt_kwargs: dict[str, Any], style_config_dict: dict[str, str] = {}) dict[str, Any][source]#
Generates default keyword arguments for initializing a
PromptSessionobject, either using default values or user-defined values, if available.- Parameters:
completer_cls – A completer class.
completer_kwargs – Keyword arguments passed to the
completer_clsclass.validator_cls – A validator class.
validator_kwargs – Keyword arguments passed to the
validator_clsclass.prompt_kwargs – Keyword arguments passed to the
PromptSessionclass.style_config_dict – Style configuration for the REPL.
- Returns:
dict[str,Any]– Keyword arguments that should be passed to thePromptSessionclass.
- get_default_validator_kwargs(validator_cls: type[Validator] | None, validator_kwargs: dict[str, Any]) dict[str, Any][source]#
Generates default keyword arguments for initializing a
Validatorobject, either using default values or user-defined values, if available.- Parameters:
validator_cls – A validator class.
validator_kwargs – Keyword arguments passed to the
validator_clsclass.
- Returns:
dict[str,Any]– Keyword arguments that should be passed to thevalidator_clsclass.
- bottom_bar: AnyFormattedText | BottomBar[source]#
Text or callable returning text, that should be displayed in the bottom toolbar of the
PromptSessionobject.Alternatively, it can be a
BottomBarobject to dynamically adjust the command description displayed in the bottom bar based on the user’s current input state.
- internal_commands_system: InternalCommandSystem[source]#
Handles and executes internal commands that are invoked in repl.
- repl_ctx: ReplContext[source]#
Context object for the current REPL session.
- class click_repl._repl.ReplGroup(prompt: str = '> ', startup: Callable[[], None] | None = None, cleanup: Callable[[], None] | None = None, repl_kwargs: dict[str, Any] = {}, **attrs: Any)[source]#
Custom
Groupsubclass for initialing the REPL.This class extends the functionality of the
Groupclass and is designed to be used as a wrapper to automatically invoke therepl()function when the group is invoked without any sub-command.- Parameters:
prompt – The prompt text for the REPL.
startup – The callback function that gets called before invoking the REPL.
cleanup – The callback function that gets invoked after exiting the REPL.
repl_kwargs – The keyword arguments that needs to be sent to the
repl()function.**attrs – Extra keyword arguments to be passed to the
click.Groupclass.
- click_repl._repl.register_repl(group: Group | None = None, *, name: str = 'repl', remove_command_before_repl: bool = False) Callable[[Group], Group] | Group[source]#
Decorator that registers
repl()as a sub-command namednamewithin thegroup.- Parameters:
group – The parent click group object to which the REPL command will be registered.
name – The name of the repl command to be in the given
group.remove_command_before_repl – Determines whether to remove the REPL command from the group, before its execution or not.
- Returns:
Callable[[Group],Group] | Group– The samegroupor a callback that returns the same group with the REPL command registered to it.- Raises:
- click_repl._repl.repl(group_ctx: Context, prompt_kwargs: dict[str, Any] = {}, cls: type[Repl] = <class 'click_repl._repl.Repl'>, **attrs: Any) None[source]#
Starts an Interactive Shell where all subcommands are available.
If stdin is not a TTY, no prompt will be printed, but only subcommands can be read from stdin.
- Parameters:
group_ctx – The current click context object.
prompt_kwargs – Parameters that should be passed to
PromptSession. These parameters configure the prompt appearance and behavior, such as prompt message, history, completion, etc.cls – Repl class to use for the click_repl app. if
None, theReplclass is used by default. This allows customization of the REPL behavior by providing a custom Repl subclass.**attrs – Extra keyword arguments to be passed to the Repl class. These additional arguments can be used to further customize the behavior of the Repl class.
Notes
You don’t have to pass the
CompleterandValidatorclass, and their arguments via theprompt_kwargsdictionary. Pass them separately in thecompleter_clsandvalidator_clsarguments respectively.Provide a text, a function, or a
BottomBarobject to determine the content that will be displayed in the bottom toolbar via thebottom_toolbarkey in theprompt_kwargsdictionary. To disable the bottom toolbar, passNoneas the value for this key.
Tokenization#
Utilities to create and manage tokens.
- class click_repl.tokenizer.Marquee(text: ListOfTokens, prefix: ListOfTokens = [])[source]#
Displays the given text in the form of a marquee in terminal.
- Parameters:
text – The text tokens that will be displayed in the marquee style, if the terminal width is insufficient to display the entire text. Otherwise, the entire text is displayed statically.
prefix – This text will be displayed as a prefix before
text, and stays at the left most end of the bottom bar and remains static.
- adjust_pointer_position() None[source]#
Updates the
pointer_positionfor the next iteration, for updating the text from the next offset location.
- get_current_text_chunk() TokenizedFormattedText[source]#
Returns the updated
textchunk, along with theprefix, that should currently be displayed in the bottom bar.- Returns:
TokenizedFormattedText– The entiretextwith theprefixif the terminal window length is sufficient. Otherwise, returns a sliced portion of thetextthat fits the current window size.
- get_full_formatted_text() TokenizedFormattedText[source]#
Returns the complete content of
textalong with theprefix, without slicing them.- Returns:
TokenizedFormattedText– The entire content of bothprefixand thetext.
- hit_boundary: bool[source]#
Indicates whether the pointer has hit either the left or right-most end.
- is_pointer_direction_left: bool[source]#
Keeps track on the current direction on pointer’s movement.
- max_wait_in_iterations: int[source]#
Maximum number of iterations the pointer can stay idle once it has hit either of the ends.
- no_of_iterations_waited_for: int[source]#
The pointer stays at the very end once it has touched the boundary, for next
no_of_iterations_waited_foriterations.
- prefix: TokenizedFormattedText[source]#
Prefix that appear before
text, and stays at the left-most end of the bottom bar and remains static.
- text: TokenizedFormattedText[source]#
Text that will be displayed in the marquee style, if the terminal width is insufficient to display the entire text. Otherwise, the entire text is displayed statically.
- class click_repl.tokenizer.TokenizedFormattedText(tokens_list: ListOfTokens, parent_token_class: str = '')[source]#
Sub-class of
FormattedText, but has custom slicing method, based on its display text.- Parameters:
tokens_list – List of Token tuples.
parent_token_class – Parent class name for the tokens in the given
tokens_list.
- content_length() int[source]#
Returns the length based on the length of text content in each token.
- Returns:
int– Total length of text content in the tokens list.
- get_text() str[source]#
Returns the entire display text from each token in a single string.
- Returns:
str– Display text altogether from all the tokens.
- slice_by_textual_content(start: int, stop: int) TokenizedFormattedText[source]#
Slices the tokens based on the text content in them.
- Parameters:
start – Starting position to slice tokens.
stop – Last position to stop slicing tokens.
- Returns:
TokenizedFormattedText– A new slice that contains the text content within that slice range.
Parsing#
Parsing functionalities for the module.
- class click_repl.parser.Incomplete(raw_str: str, parsed_str: str)[source]#
Stores the last incomplete text token in the current prompt input, that requires suggestions. It stores the incomplete last text token in its raw form in
raw_strattribute, and in its parsed form inparsed_strattribute. The parsed form has no unpaired quotes surrounding it if the draw form had any.- Parameters:
raw_str – Raw form of the incomplete text.
parsed_str – Parsed form of the raw incomplete text.
- expand_envvars() str[source]#
Expands Environmental variables in
parsed_strand returns it as a new string.- Returns:
str– String with all the Environmental inparsed_strvariables expanded.
- class click_repl.parser.ReplInputState(cli_ctx: Context, current_ctx: Context, args: tuple[str, ...])[source]#
Describes about the current input state of the text in the current prompt. It includes the details about the current click group, command and parameter the user is requesting autocompletions for.
- Parameters:
cli_ctx – The click context object of the main group.
current_ctx – The most recently created click context object, after parsing
args.args – List of text that’s entered in the prompt.
- get_current_arg(current_command: Command) Argument | None[source]#
Parse the
current_ctxand returns the current click argument from the givencurrent_commandthat’s been requested in the prompt.- Parameters:
current_command – The current click command.
- Returns:
click.Argument | None– The current click argument, if requested, in the prompt.
- get_current_group_and_command() tuple[Group, Command | None][source]#
Parse the
current_ctxand returns the current click group and command that’s been requested in the prompt.- Returns:
tuple[Group,Command | None]– The current click group and command, if requested, in the prompt.
- get_current_opt(current_command: Command) Option | None[source]#
Parse the
current_ctxand returns the current click option from the givencurrent_commandthat’s been requested in the prompt.- Parameters:
current_command – The current click command.
- Returns:
click.Option | None– The current click option, if requested, in the prompt.
- get_current_param(current_command: Command) Parameter | None[source]#
Parse the
current_ctxand returns the current click parameter from the givencurrent_commandthat’s been requested in the prompt.- Parameters:
current_command – The current click command.
- Returns:
Parameter | None– The current click parameter, if requested, in the prompt.
- parse() tuple[Group, Command | None, Parameter | None][source]#
Parse the :attr`~.current_ctx` and returns the current click group, command and paramter that’s been requested in the prompt.
- Returns:
tuple[Group,Command | None,Parameter | None]– The current click group, command and parameter, if requested, in the prompt.
- click_repl.parser._resolve_incomplete(document_text: str) tuple[tuple[str, ...], Incomplete][source]#
Resolves the last incomplete string token from the prompt to generate suggestions based on it.
- Parameters:
document_text – The text currently in the prompt.
- Returns:
tuple[tuple[str,...],Incomplete]–- A tuple that containing:
A list of text, lexically split from the text in prompt.
An Incomplete object that has the recent incomplete text token.
- click_repl.parser._resolve_repl_input_state(cli_ctx: Context, current_ctx: Context, args: tuple[str, ...]) ReplInputState[source]#
Initializes
ReplInputStateclass if its arguments are not cached. Otherwise, returns the cached ReplInputState object.- Parameters:
cli_ctx – The click context object of the parent group.
current_ctx – The current click context object.
args – Tuple of strings containing the arguments.
- Returns:
ReplInputState– Object that describes the current input state.
- click_repl.parser._resolve_state(ctx: Context, document_text: str) tuple[Context, ReplInputState, Incomplete][source]#
Resolves the input state of the arguments in the REPL prompt.
- Parameters:
ctx – The current click context object of the parent group.
document_text – The text currently in the prompt.
- Returns:
tuple[Context,ReplInputState,Incomplete]–- A tuple that contains:
click context object constructed from parsing the given input from prompt.
Current REPL input state object.
Object that holds the incomplete text token that requires suggestions.
Utils#
Utilities to facilitate the functionality of the module.
- click_repl.utils.is_param_value_incomplete(ctx: Context, param: Parameter, check_if_tuple_has_none: bool = True) bool[source]#
Checks whether the given parameter has recieved its values completely.
- Parameters:
ctx – A click context object corresponding to the parameter.
param – A click parameter object to check its value after parsing.
check_if_tuple_has_none – Indicates whether the given parameter stores multiple values in a tuple, and the tuple has
Nonein it.
- Returns:
bool–Trueif the given parameter has received all of its necessary values from the prompt, otherwiseFalse.
- click_repl.utils.iterate_command_params(command: Command) Generator[Parameter, None, None][source]#
Iterate over parameters of a command in an order such that the
Argumentwithnargs= -1 will be yielded at the very end.- Parameters:
command – A click command object to iterate over its parameters.
- Yields:
click.Parameter– The parameters of the givencommand, yielding thenargs=-1parameter at last.- Raises:
ArgumentPositionError – If the
Argumentobject withnargs=-1is not defined at the very end among other parameters.
Exceptions#
Exceptional classes required for the module.
- exception click_repl.exceptions.ArgumentPositionError(command: Command, argument: Argument, position: int)[source]#
Exception raised when an
Argumentwithnargs= -1 is not defined at the rightmost end of the parameter list.This exception indicates that the given command has an argument with
nargs=-1defined within the other parameters. However, an argument withnargs=-1must be defined at the end of the parameter list. This is because an argument withnargs=-1consumes all the incoming values as the remaining values from the REPL prompt, and any other parameter defined after it will not receive any value.- Parameters:
command – The click command object that contains the argument.
argument – The click argument object that violates the position rule.
position – The index of the disarranged
nargs=-1argument in the parameter list of the given command.
- exception click_repl.exceptions.ExitReplException[source]#
Exception raised to stop the REPL of the click_repl app.
- exception click_repl.exceptions.InternalCommandException[source]#
Base Class for all exceptions raised by the
InternalCommandSystem.This class is used to replace errors raised inside the
InternalCommandSystemclass in order to display their error messages separately in the REPL.
- exception click_repl.exceptions.InternalCommandNotFound[source]#
Exception raised when the given command name is not an internal command.
- exception click_repl.exceptions.ParserError[source]#
Exception raised when parsing given input for click objects fails.
- exception click_repl.exceptions.PrefixNotFound[source]#
Exception raised when the prefix of an internal command is not found while attempting to execute a query.
- exception click_repl.exceptions.SamePrefix(prefix_str: str)[source]#
Exception raised when both
system_command_prefixinInternalCommandSystemare assigned as the same prefix string.- Parameters:
prefix_str – The prefix string that is assigned to both
internal_command_prefixandsystem_command_prefix.
- exception click_repl.exceptions.WrongType(var: Any, var_name: str, expected_type: str)[source]#
Exception raised when an object with an invalid type is passed to one of the methods in
InternalCommandSystem.- Parameters:
var – The variable that has wrong or unexpected type.
var_name – The name of the variable passed through the
varparameter.expected_type – A string that describes the expected type.
Custom Click Utilities#
Customized click module utilities with modifications to benefit the functionality of click-repl module.
Parsers#
- class click_repl.click_custom.parser.ArgumentParamParser(obj: CoreArgument, dest: str | None, nargs: int = 1)[source]#
Subclass of
Argument, but modified to fillNonefor empty values for anArgumentwithnargs!= 1.- Parameters:
obj – The click argument object.
dest – The
nameof theobj.nargs – The
nargsof theobj.
References
Argument
- class click_repl.click_custom.parser.ReplOptionParser(ctx: Context)[source]#
Subclass of
OptionParser, modified to fill inNonevalues for empty values forArgumentwithnargs!= 1.- Parameters:
ctx – The current click context object, constructed from the text currently in the prompt.
References
- click_repl.click_custom.parser.get_option_flags_sep(option_names: list[str]) str[source]#
Returns the character to separate the given list of option names.
- Parameters:
option_names – List of option names
- Returns:
str– Character that separates the option names
- click_repl.click_custom.parser.order_option_names(option_names: Sequence[str]) list[str][source]#
Orders all the option names based on the length of their prefixes.
- Parameters:
option_names – List of option names of a click option.
- Returns:
list[str]– List of option names, ordered based on their prefix length.
Shell Completion#
Utils#
Others#
Global Values#
Global variables, values, and functions that are accessed across all the files in this module.
- click_repl.globals_.get_current_repl_ctx() ReplContext | NoReturn[source]#
- click_repl.globals_.get_current_repl_ctx(silent: bool = False) ReplContext | NoReturn | None
Retrieves the current click-repl context.
This function provides a way to access the context from anywhere in the code. This function serves as a more implicit alternative to the
pass_context()decorator.- Parameters:
silent – If set to
True, the function returnsNoneif no context is available. The default behavior is to raise aRuntimeError.- Returns:
ReplContext| None – REPL context object if available, orNoneifsilentisTrue.- Raises:
RuntimeError – If there’s no context object in the stack and
silentisFalse.
Style Config#
Default tokens style configurations.
- click_repl.styles.DEFAULT_BOTTOMBAR_STYLE_CONFIG[source]#
Default token style configuration for
BottomBar
- click_repl.styles.DEFAULT_COMPLETION_STYLE_CONFIG[source]#
Default token style configuration for
ClickCompleter
- click_repl.styles.DEFAULT_PROMPTSESSION_STYLE_CONFIG[source]#
Default token style configuration for
PromptSession
Proxies#
Proxy objects to modify the parsing method of click objects.
- class click_repl.proxies.Proxy(obj: T)[source]#
Base class for creating proxy objects that customize attribute access behavior.
- Parameters:
obj – Object to which attribute access is delegated.
- get_obj() Any[source]#
Gets the underlying object.
- Returns:
Any– The underlying object to which attribute access is delegated.
- proxy_delattr(name: str) None[source]#
Proxy attribute deletion for internal use.
- Parameters:
name – The name of the attribute to delete.
- proxy_getattr(name: str) Any[source]#
Proxy attribute access for internal use.
- Parameters:
name – The name of the attribute to access.
- Returns:
Any– The value of the accessed attribute.
- proxy_setattr(name: str, value: Any) None[source]#
Proxy attribute assignment for internal use.
- Parameters:
name – The name of the attribute to assign.
value – The value to assign to the attribute.
- revoke_changes() None[source]#
Revoke any changes made to the underlying object.
- Raises:
NotImplementedError – This method is meant to be overridden by subclasses.
- class click_repl.proxies.ProxyArgument(obj: Argument)[source]#
Proxy class for
Argumentobjects, enabling modification of their behavior during the processing and consuming values.This class overrides the
process_value()method to return missing values as they are, even if they are incomplete or not provided.- Parameters:
obj – The
Argumentobject that needs to be proxied.
- class click_repl.proxies.ProxyCommand(obj: Command)[source]#
Proxy class for
Commandobjects that modifies their options parser.This class overrides the
make_parser()method to use the custom parser implementation provided byReplOptionParser.- Parameters:
obj – The click command object that needs to be proxied.
- make_parser(ctx: Context) ReplOptionParser[source]#
Creates the underlying option parser for this command.
- revoke_changes() None[source]#
Revoke any changes made to the underlying object.
- Raises:
NotImplementedError – This method is meant to be overridden by subclasses.
- class click_repl.proxies.ProxyCommandCollection(obj: CommandCollection)[source]#
Proxy class for
ProxyCommandCollectionobjects that modifies their options parser.This class overrides the
make_parser()method to use the custom parser implementation provided byReplOptionParser.- Parameters:
obj – The click group object that needs to be proxied.
- class click_repl.proxies.ProxyGroup(obj: Group)[source]#
Proxy class for
Groupobjects that modifies their options parser.This class overrides the
make_parser()method to use the custom parser implementation provided byReplOptionParser.- Parameters:
obj – The click group object that needs to be proxied.
- revoke_changes() None[source]#
Revoke any changes made to the underlying object.
- Raises:
NotImplementedError – This method is meant to be overridden by subclasses.
- class click_repl.proxies.ProxyOption(obj: Option)[source]#
Proxy class for
Optionobject, enabling modification of their behavior during the processing and consuming values and also prevent prompting for value in the REPL.This class overrides the
process_value()method to return missing values as they are, even if they are incomplete or not provided.- Parameters:
obj – The
click.Optionobject that needs to be proxied.
- class click_repl.proxies.ProxyParameter(obj: Parameter)[source]#
Generic proxy class for
Parameterobjects that modifies its behavior for processing and consuming values.This class overrides the
process_value()method to return missing values as they are, even if they are incomplete or not provided.- Parameters:
obj – The
click.Parameterobject that needs to be proxied.
- click_repl.proxies.create_proxy_command(obj: Command) ProxyCommand[source]#
- click_repl.proxies.create_proxy_command(obj: Group) ProxyGroup
- click_repl.proxies.create_proxy_command(obj: CommandCollection) ProxyCommandCollection
Wraps the given
Commandobject within a proxy object.- Parameters:
obj – Command object that needs to be wrapped in a proxy object.
- Returns:
ProxyCommand | ProxyGroup | ProxyCommandCollection– Proxy wrapper for theCommandobjects.
- click_repl.proxies.create_proxy_param(obj: Parameter) Parameter[source]#
- click_repl.proxies.create_proxy_param(obj: Option) ProxyOption
- click_repl.proxies.create_proxy_param(obj: Argument) ProxyArgument
Wraps the given
Parameterobject within a proxy object.- Parameters:
obj – Parameter object that needs to be wrapped in a proxy object.
- Returns:
ProxyParameter– Proxy wrapper for theParameterobjects.