click_extra.config.option module¶

        classDiagram
  ChainMap <|-- _DeepChainMap
  ConfigDiscovery <|-- ConfigOption
  Enum <|-- Sentinel
  ExtraOption <|-- ConfigOption
  ExtraOption <|-- NoConfigOption
  ExtraOption <|-- ValidateConfigOption
  ParamStructure <|-- ConfigOption
  ValueError <|-- _EmptyConfigError
    

Utilities to load parameters and options from a configuration file.

Hint

The whole namespace designates configuration files by the short name config: not conf, cfg, configuration or settings. In the context of a CLI, config reads as nothing else.

Dotted keys in configuration files (like "subcommand.option": value) are automatically expanded into nested dicts before merging, so users can freely mix flat dot-notation and nested structures in any supported format.

click_extra.config.option.get_app_dir(app_name, roaming=True, force_posix=False)¶

click.get_app_dir()’s Unix branch, taken on every platform.

Returns an expanded path like the original, since a caller resolves it before Click Extra shrinks the home prefix back to ~ for display. XDG_CONFIG_HOME is deliberately ignored: honoring it would put the host back into the rendered output.

click_extra.config.option.CONFIG_OPTION_NAME = 'config'¶

Hardcoded name of the configuration option.

The --config and --no-config options share this name, so they compete with each other to either set a path pattern or disable the use of any configuration file at all.

click_extra.config.option.DEFAULT_EXCLUDED_PARAMS = ('config', 'export_config', 'params', 'validate_config', 'version')¶

Default parameter IDs to exclude from the configuration file.

Defaults to:

  • --config option, which cannot be used to recursively load another configuration file.

  • --export-config flag, which like --params introspects the CLI and exits, so it has no place in the configuration it would export.

  • --params flag, which is like --help and stops the CLI execution.

  • --validate-config option, which belongs to the same self-referential config machinery as --config and --export-config.

  • --version, which is not a configurable option per-se.

--help is excluded too (it makes no sense to have a configuration file always force a CLI to show the help and exit), but is deliberately absent from this tuple: unlike the entries above, click-extra does not control that option’s internal name. It is resolved at runtime instead, in ConfigOption.excluded_params, so a rename on Click’s own side does not silently stop excluding it.

click_extra.config.option.THEMES_CONFIG_KEY: str = 'themes'¶

Sub-key under [tool.<cli>] where user-defined themes live in config.

Used by ConfigOption to find [tool.<cli>.themes.<name>] tables, build them via HelpTheme.from_dict, and stash the result on ctx.meta[click_extra.context.THEME_OVERRIDES]. The constant is the single source of truth shared by _builtin_config_validators, ConfigOption._apply_theme_overrides, and click_extra.theme.themes_from_config().

class click_extra.config.option.Sentinel(*values)[source]¶

Bases: Enum

Enum used to define sentinel values.

Note

This reuses the pattern of click._utils.Sentinel.

NO_CONFIG = <object object>¶
VCS = <object object>¶
click_extra.config.option.NO_CONFIG = Sentinel.NO_CONFIG¶

Sentinel used to indicate that no configuration file must be used at all.

click_extra.config.option.VCS = Sentinel.VCS¶

Sentinel used to stop parent directory walking at the nearest VCS root.

class click_extra.config.option.ConfigOption(param_decls=None, *, metavar='LOCATION', type=UNPROCESSED, help='Location of the configuration file. Supports local path with glob patterns or remote URL.', is_eager=True, expose_value=False, file_format_patterns=None, file_pattern_flags=None, show_file_patterns=None, roaming=True, force_posix=False, search_pattern_flags=None, search_parents=False, stop_at=Sentinel.VCS, cascade=False, excluded_params=None, included_params=None, strict=False, config_schema=None, schema_strict=False, fallback_sections=(), config_validators=(), **kwargs)[source]¶

Bases: ConfigDiscovery, ExtraOption, ParamStructure

A pre-configured option adding --config LOCATION.

Caution

The first ConfigOption a process builds replaces click.Group.parse_args for all of it. The replacement is how the subcommands the configuration names still run in the two cases the option never sees, on a group class click-extra does not own. One is a bare invocation, for which Click prints its no_args_is_help screen before it runs any parameter. The other is a subgroup, which holds no option of its own. Every other call goes to Click unchanged, as does each group of a CLI carrying no ConfigOption.

Takes as input a path to a file or folder, a glob pattern, or an URL.

  • is_eager is active by default so the callback gets the opportunity to set the default_map of the CLI before any other parameter is processed.

  • default is set to the value returned by self.default_pattern(), which is a pattern combining the default configuration folder for the CLI (as returned by click.get_app_dir()) and all supported file formats.

    Attention

    Default search pattern must follow the syntax of wcmatch.glob.

  • excluded_params are parameters which, if present in the configuration file, will be ignored and not applied to the CLI. Items are expected to be the fully-qualified ID of the parameter, as produced in the output of --params. Will default to the value of DEFAULT_EXCLUDED_PARAMS, plus the CLI’s --help option, resolved at runtime.

  • included_params is the inverse of excluded_params: only the listed parameters will be loaded from the configuration file. Cannot be used together with excluded_params.

file_format_patterns: dict[ConfigFormat, tuple[str, ...]]¶

Mapping of ConfigFormat to their associated file patterns.

Can be a string or a sequence of strings. This defines which configuration file formats are supported, and which file patterns are used to search for them.

Note

All formats depending on third-party dependencies that are not installed will be ignored.

Attention

File patterns must follow the syntax of wcmatch.fnmatch.

auto_file_formats¶

Whether the format set was inherited instead of chosen by the developer.

True when no file_format_patterns was provided, so the set is whatever the installed extra dependencies enable. It ranges from 3 patterns on a bare install to 14 with every extra, which is an artifact of the environment rather than a decision the CLI made.

Only collapse_default() reads it, and only when show_file_patterns is left at None.

show_file_patterns¶

Whether the help screen prints the file patterns of the default.

Follows the tri-state convention of Click Extra’s other display settings:

  • None prints them when the developer chose the format set, and hides them when it was inherited from the install.

  • True always prints them, which is how a CLI advertises the formats its own dependencies enable.

  • False always hides them.

See collapse_default() for what each state renders.

force_posix¶

Configuration for default folder search.

roaming and force_posix are fed to click.get_app_dir() to determine the location of the default configuration folder.

search_parents: bool¶

Indicates whether to walk back the tree of parent folders when searching for configuration files.

stop_at: Path | str | Literal[Sentinel.VCS] | None¶

Boundary for parent directory walking.

  • None: walk up to filesystem root.

  • VCS: stop at the nearest VCS root, whichever system marks it (see VCS_DIRS) (default).

  • A Path or str: stop at that directory.

cascade¶

Merge every discovered configuration file instead of stopping at the first parseable one.

When True, all files found by auto-discovery (the app-dir search, including the parent walk when search_parents=True, plus the pyproject.toml CWD search when enabled) are loaded and layered into the context’s default_map. The most local file wins each key, in the sections of subcommands too: a pyproject.toml found near the CWD overrides the app-dir config, which overrides files found higher up the parent walk. A list comes whole from the most local file setting it.

An explicit --config value never cascades: it pins a single source, whatever the pattern matches.

Defaults to False: the first successfully parsed file wins.

extra_excluded_params: frozenset[str]¶

Additional exclusions merged into the dynamic excluded_params default.

Populated by Command’s excluded_params forwarding, which is additive: the default blocklist (--config, --version, --help, …) is preserved and the forwarded IDs are unioned into it when the property resolves. Ignored when an explicit excluded_params was frozen on the instance, as the property is then never consulted.

included_params: frozenset[str] | None¶

Allowlist of parameter IDs, mutually exclusive with excluded_params.

None disables the allowlist. Otherwise build_param_trees() walks only the subcommands an allowed ID lies under, and resolves the parameters it reaches into excluded_params.

strict¶

Defines the strictness of the configuration loading.

  • If True, raise an error if the configuration file contain parameters not recognized by the CLI.

  • If False, silently ignore unrecognized parameters.

config_schema¶

Optional schema for structured access to configuration values.

When set, the app’s configuration section is extracted from the parsed config file, normalized (hyphens replaced with underscores), flattened (nested dicts joined with _), and passed to this callable to produce a typed configuration object.

Supports:

  • Dataclass types: detected via __dataclass_fields__. Keys are normalized, nested dicts are flattened, and the result is filtered to known fields before instantiation. This allows nested config sections (like [tool.myapp.sub-section]) to map directly to flat dataclass fields (like sub_section_key).

  • Any callable dict → T: called directly with the raw dict. Works with Pydantic’s Model.model_validate, attrs, or custom factory functions. The caller is responsible for key normalization and flattening.

The resulting object is stored in ctx.meta[click_extra.context.TOOL_CONFIG] and can be retrieved via get_tool_config.

schema_strict¶

Strictness for schema validation (separate from strict).

  • If True, raise ValueError when the config section contains keys that do not match any dataclass field (after normalization and flattening). Only applies when config_schema is a dataclass.

  • If False, ignore unrecognized keys. When the section is schema-only (included_params=()), a warning still names them: see warn_unknown in make_schema_callable().

Note

This is distinct from strict, which controls whether config keys not matching CLI parameters are rejected. schema_strict validates against dataclass fields instead.

fallback_sections: Sequence[str]¶

Legacy section names to try when the app’s own section is empty.

Useful when a CLI tool has been renamed: old configuration files that still use [tool.old-name] (TOML), old-name: (YAML), or {"old-name": …} (JSON) are recognized with a deprecation warning. Works with all configuration formats.

schema_warn_unknown: bool¶

Warn on config keys unknown to the schema, in lax mode.

Inferred, not user-supplied: an explicitly empty included_params means no CLI parameter is merged from the app’s config section, so the section is schema-only and any key the schema does not know is a typo worth a warning. Forwarded to make_schema_callable() and the validation pipeline as warn_unknown.

config_validators: tuple[ConfigValidator, ...]¶

Extension validators for sub-trees of the configuration file.

Each ConfigValidator targets a dotted extension_path relative to the app section. Validators run after click-extra’s built-in CLI-parameter strict check (during --validate-config) and after the schema callable produces the typed configuration object (during normal config loading).

The list is seeded with click-extra’s built-in validators (the one for [tool.<cli>.themes.<name>] tables, see click_extra.theme.validate_themes_config()); user-supplied validators are appended after them. App code that registers its own validator on the same extension_path runs alongside the built-in: both validators are called, both sets of errors surface.

apply_command_settings(*, config_schema=None, config_strict=False, schema_strict=False, fallback_sections=(), config_validators=(), included_params=None, excluded_params=None, cascade=False)[source]¶

Take over the configuration settings a command was built with.

Command accepts the settings of its default --config option as keyword arguments of its own, so a CLI tunes that option without replacing the whole default parameter list, and hands them over here once its parameters are known. Each argument defaults to the value meaning “leave the option as it is”.

excluded_params is additive, where the option’s own argument replaces the default blocklist: the forwarded IDs join it, through extra_excluded_params while the blocklist is still the dynamic default, and straight into the frozen value otherwise. The config_validators join click-extra’s built-in ones the same way, as they do when passed to the option itself.

Raises:

ValueError – when excluded_params is forwarded to an option carrying its own included_params, the two filters being mutually exclusive.

Return type:

None

property file_pattern_flags: int[source]¶

Flags provided to all calls of wcmatch.fnmatch.

Applies to the matching of file names against supported format patterns specified in file_format_patterns. None at construction picks NEGATE | SPLIT.

Important

The SPLIT flag is always forced, as our multi-pattern design relies on it.

Resolved on first use rather than in __init__, so building the option imports nothing from wcmatch.

property search_pattern_flags: int[source]¶

Flags provided to all calls of wcmatch.glob.

Applies to both the default pattern and any user-provided pattern. None at construction picks GLOBSTAR | FOLLOW | DOTGLOB | BRACE | SPLIT | GLOBTILDE | NODIR.

Important

The BRACE flag is always forced, so that multi-format default patterns using {pat1,pat2,...} syntax expand correctly.

The NODIR flag is always forced, to optimize the search for files only.

Resolved on first use rather than in __init__, so building the option imports nothing from wcmatch.

property excluded_params: frozenset[str][source]¶

Generates the default list of fully-qualified IDs to exclude.

Danger

Resolved once, on first read, and only when the user did not provide a list of their own.

The IDs are rooted at the CLI name, which only the running context knows: hence a property, read within that context, rather than a value set by the constructor.

property file_pattern: str[source]¶

Compile all file patterns from the supported formats.

Uses , (comma) notation to combine multiple patterns, suitable for wcmatch brace expansion ({pat1,pat2,...}).

Returns a single pattern string.

default_pattern()[source]¶

Returns the default pattern used to search for the configuration file.

Defaults to the patterns of every format in file_format_patterns, under <app_dir>: <app_dir>/{*.toml,*.json,*.ini,…}. Where <app_dir> is produced by the click.get_app_dir() method. The result depends on OS and is influenced by the roaming and force_posix properties.

Multiple file format patterns are wrapped with {…} brace-expansion syntax so that wcmatch.glob correctly applies the directory prefix to every sub-pattern.

Note

A CLI wanting another folder layout, like the one platformdirs computes, passes its own pattern to default instead. That keeps the layout a choice of the CLI rather than a dependency of this package: see the documentation.

Return type:

str

get_help_extra(ctx)[source]¶

Replaces the default value of the configuration option.

Display a pretty path that is relative to the user’s home directory:

~/folder/my_cli/{*.toml,*.json,*.ini}

Instead of the full absolute path:

/home/user/folder/my_cli/{*.toml,*.json,*.ini}

Caution

This only applies when the GLOBTILDE flag is set in search_pattern_flags.

An inherited format set is then reduced to the folder it searches, as described in collapse_default().

Return type:

OptionHelpExtra

render_default(ctx)[source]¶

The default search pattern, as a portable home-relative path.

Keeps the whole pattern, file patterns included. The help screen collapses an inherited set on top of this with collapse_default(), but a consumer with room for the files (the FILES section of a man page) calls this method instead. A URL is returned as given.

Return type:

str

collapse_default(default)[source]¶

Reduce an inherited default pattern to the folder it searches.

A CLI installed with every extra searches 15 file patterns, so its default renders as a 136-character glob. The help screen has no space for it and no place to break it, so Click splits it mid-word:

[default: ~/.config/hello/{*.
toml,*.yaml,*.yml,*.json,*.json5,*.jwcc,*.jsonc,
*.hjson,*.ini,*.xml,*.plist,*.sqlite,*.sqlite3,*
.conf,pyproject.toml}]

Rendering the folder alone answers the question a reader opens --help for, on one line, and keeps the answer the same on every install:

[default: ~/.config/hello/]

A developer who passed file_format_patterns chose that set, so it is displayed in full: the pattern is short enough to read, and the help screen is where the choice shows up. show_file_patterns overrides that reading in either direction, and True is what a CLI advertising its formats wants: the set is computed from the installed dependencies at each invocation, so the help screen reports what that install can really parse. The complete pattern of any CLI stays available in the output of --params.

The trailing separator marks the value as a folder, since it is a search base and not a location the option accepts back.

Return type:

str

parse_conf(content, formats, location=None)[source]¶

Parse the content with the given formats.

Tries to parse the given raw content string with each of the given formats, in order. Yields the resulting data structure for each successful parse.

location is the path the content was read from. It is only needed by formats that cannot be parsed from a text payload, like SQLITE, which is read straight from its file, and the binary variant of PLIST, which only exists on disk. Such formats are skipped when location is missing or is not a local file.

Attention

Formats whose parsing raises an exception or does not return a dict are considered a failure and are skipped. A format parsing the content to None, as YAML does for a document of comments only, yields an empty dict instead.

This follows the parse, don’t validate principle.

Return type:

Iterable[dict[str, Any] | None]

read_and_parse_all_conf(pattern)[source]¶

Search for every parseable configuration file matching pattern.

Yields (location, parsed_conf) pairs in discovery order, which is the most local first: the original search location, then each parent directory when parent search is enabled. Files already yielded (as matched by their resolved location) are skipped, as are files that parse to an empty configuration.

Raises FileNotFoundError if no file at all matched the pattern.

Return type:

Iterable[tuple[Path | str, dict[str, Any]]]

read_and_parse_conf(pattern)[source]¶

Search for a parseable configuration file.

Returns the location and data structure of the first configuration matching the pattern.

Only return the first match that:

  • exists,

  • is a file, or a character device or a named pipe that pattern names,

  • is not empty,

  • match file format patterns,

  • can be parsed successfully, and

  • produce a non-empty data structure.

Raises FileNotFoundError if no configuration file was found matching the criteria above.

Returns (None, None) if files were found but none could be parsed.

Return type:

tuple[Path | str, dict[str, Any]] | tuple[None, None]

load_ini_config(content)[source]¶

Utility method to parse INI configuration file.

Internal convention is to use a dot (., as set by PARAM_PATH_SEP) in section IDs as a separator between levels. This is a workaround the limitation of INI format which doesn’t allow for sub-sections.

Each value is converted to the type of the parameter its section and key address, like [my-cli.subcommand] for the options of subcommand.

Returns a ready-to-use data structure.

Return type:

dict[str, Any]

load_argfile_config(content)[source]¶

Utility method to parse a plain-text argfile configuration file.

The file holds command-line tokens, one option per line, in the style of mpv’s and yt-dlp’s configuration files:

# Comments start with a hash sign.
--option-name some value
--flag

Tokens are split with shlex.split(), so shell quoting rules apply and a # starts a comment. Each option is matched against the CLI’s root-level parameter declarations, and its value is converted to the parameter’s Python type, like load_ini_config() does. A boolean flag needs no value: its primary declaration sets it to True, its secondary one (--no-*) to False. An option flagged multiple accumulates one list item per occurrence. Unknown options are kept under a normalized key so the strict check can reject them like any other unrecognized configuration key, while positional tokens are skipped; subcommand options cannot be addressed from an argfile.

Returns a ready-to-use data structure, wrapped in the app’s section name like the [my-cli] section of the other formats.

Raises:

ValueError – the content cannot be tokenized, or an option is missing its value.

Return type:

dict[str, Any]

load_sqlite_config(path)[source]¶

Utility method to parse a SQLite configuration database.

The database holds a single SQLITE_CONFIG_TABLE table of key/value rows. Keys are parameter paths, with a dot (., as set by PARAM_PATH_SEP) separating each level, like my-cli.default.int_param. Values are JSON-encoded, which carries every type the other formats do: booleans, numbers, strings, lists and nested objects alike.

Returns a ready-to-use data structure.

Note

sqlite3 is imported here and not at the top of the module, like the optional parsers of parse_content(). A distribution can ship a Python without the SQLite bindings, and an unconditional import would then break every CLI at import time. ConfigFormat.SQLITE.enabled reports whether they are there, and the format is disabled if they are not.

Return type:

dict[str, Any]

load_plist_config(path)[source]¶

Utility method to parse a plist configuration file.

The file is read as raw bytes and handed to the standard library’s plistlib, which transparently decodes both the XML and the binary variants of the format. The XML variant also parses from a text payload through parse_content(), which is how a plist fetched over http:// or https:// is loaded.

Returns a ready-to-use data structure.

Return type:

dict[str, Any]

load_xml_config(content)[source]¶

Utility method to parse an XML configuration document.

parse_xml() collects the elements repeating a tag into a list, so a lone element reads as its text. An element naming a parameter that takes several values reads as a one-item list instead: XML has no other way to spell a list of one. Element names match parameters through canonical_param_name(), so the kebab-case spelling counts too.

Returns a ready-to-use data structure.

Return type:

dict[str, Any]

merge_default_map(ctx, user_conf)[source]¶

Save the user configuration into the context’s default_map.

Merge the user configuration into the pre-computed template structure, which filters out all unrecognized options not supported by the command, then hand the result to _install_default_map().

Opaque sub-trees declared by the schema or by registered ConfigValidator instances are stripped from the conf before dotted-key expansion and the CLI-parameter strict check, so user-controlled keys (like mappings whose keys are data, not flag names) neither split on a dot nor trip strict=True.

Note

load_conf() installs the same merged configuration, as part of the validation it runs: it does not call this method.

Raises:

ValidationError – in strict mode, on an invalid dotted key or a key matching no parameter.

Return type:

None

load_conf(ctx, param, path_pattern)[source]¶

Fetch parameter values from a configuration file and set them as defaults.

User configuration is merged to the context’s default_map, like Click does.

Relying on Click’s default_map keeps the precedence: direct CLI parameters, environment variables or interactive prompts take precedence over any values from the config file.

Hint

Once loading is complete, the resolved file path and its full parsed content are stored in ctx.meta[click_extra.context.CONF_SOURCE] and ctx.meta[click_extra.context.CONF_FULL] respectively. This is the recommended way to identify which configuration file was loaded.

There is no ParameterSource.CONFIG_FILE enum member: ParameterSource is a closed enum in Click, and monkeypatching it would be fragile. Config values end up in default_map, so Click reports them as ParameterSource.DEFAULT_MAP, which is accurate.

Return type:

None

handle_parse_result(ctx, opts, args)[source]¶

Apply the reserved subcommand keys, once the configuration is loaded.

load_conf() runs as this option’s callback, from inside the super() call below, so the parsed document is already in ctx.meta when inject_reserved_subcommands() reads it.

Returning a rewritten args is what makes _default_subcommands and _prepend_subcommands work on any group class: Click threads the residual arguments through each parameter in turn, then hands the final list to Group.parse_args, which splits it into the subcommands to dispatch. The group can be of a class click-extra does not own, so the option carries the feature instead of the group.

Two cases never come here. On a bare invocation, Click raises the no_args_is_help screen before it runs any parameter. A subgroup reached through this option holds no option of its own. The click.Group.parse_args this class installs covers both.

Before loading, it reads the verbosity the command line asks for (see requested_level()), so load_conf() can keep its status lines quiet under -q or a --verbosity above WARNING.

Return type:

tuple[Any, list[str]]

class click_extra.config.option.NoConfigOption(param_decls=None, *, help='Ignore all configuration files and only use command line parameters and environment variables.', is_flag=True, flag_value=Sentinel.NO_CONFIG, is_eager=True, expose_value=False, **kwargs)[source]¶

Bases: ExtraOption

A pre-configured option adding --no-config.

This option is supposed to be used alongside the --config option (ConfigOption) to allow users to explicitly disable the use of any configuration file.

This is especially useful to debug side-effects caused by autodetection of configuration files.

flag_value=NO_CONFIG is the Sentinel enum member that signals “skip configuration loading” to ConfigOption. Click picks type=UNPROCESSED for a flag_value of a non-basic type, so the sentinel passes through Option unchanged.

See also

An alternative implementation of this class would be to create a custom click.ParamType instead of a custom Option subclass. Here is for example.

check_sibling_config_option(ctx, param, value)[source]¶

Ensure that this option is used alongside a ConfigOption instance.

Return type:

None

class click_extra.config.option.ValidateConfigOption(param_decls=None, *, type=UNPROCESSED, metavar='LOCATION', is_eager=True, expose_value=False, help='Validate the configuration file and exit.', **kwargs)[source]¶

Bases: ExtraOption

A pre-configured option adding --validate-config LOCATION.

Loads the config file at the given location, validates it against the CLI’s parameter structure in strict mode, reports results, and exits.

Note

The value is left UNPROCESSED so it accepts everything ConfigOption accepts: a file, a folder, a glob pattern, or an http:// or https:// URL. Both options read their value the same way, so a configuration a CLI can load is a configuration it can also validate.

validate_config(ctx, param, value)[source]¶

Load, parse, and validate the configuration file, then exit.

Validation runs three checks in order, every one of them under the same ValidationError shape so the reported path is always rooted at the configuration file:

  1. CLI-parameter strict check on the non-opaque part of the document.

  2. Schema processing, if a config_schema is configured: catches type errors and unknown keys inside the dataclass-described section.

  3. Each registered ConfigValidator runs against its declared opaque sub-tree.

Every detected error is emitted before exiting, so a single --validate-config run surfaces the full list of fixes the user needs to apply.

Return type:

None