click_extra.config package¶

Configuration file loading, format parsing, and schema validation.

This package gathers the layers behind --config, --no-config, --validate-config and --export-config:

  • flags: translate a configuration table into command-line flags, for tools that mirror their config keys as options but cannot read the table themselves.

  • formats: the supported file formats and the generic, stateless helpers to read, serialize, auto-detect, and resolve them.

  • schema: the generic schema-building and validation engine, applicable to any dataclass.

  • builtin: click-extra’s own configuration schema (one concrete application of the engine), read by the click-extra CLI alone.

  • discovery: the search for configuration files, in a folder, its parents, a URL or the nearest pyproject.toml.

  • option: the --config / --no-config / --validate-config option classes, and the validators they register by default.

  • export: the --export-config option.

  • subcommands: resolution of the reserved _default_subcommands and _prepend_subcommands keys.

The package re-exports the symbols below, so consumers can import them from click_extra.config:

  • every public symbol of export, flags and schema;

  • from option, the three option classes, the NO_CONFIG and VCS sentinels, and THEMES_CONFIG_KEY;

  • from formats, the ConfigFormat enumeration, the SERIALIZABLE_FORMATS and SQLITE_CONFIG_TABLE constants, and the helpers that identify, parse or serialize a document in any format.

Import any other symbol from its own module, like the ConfigDiscovery mixin.

click_extra.config.config_table_to_flags(table)[source]¶

Translate a mapping of configuration keys into long-form CLI flags.

For tools whose command-line options mirror their configuration keys but which cannot read the table themselves (no --config support, no native config file). Follows the conventional mapping:

  • key = True → --key

  • key = "value" (or a number) → --key=value

  • key = ["a", "b"] → --key=a --key=b (one flag per item)

  • key = False is skipped: there is no universal --no-<key> form.

Keys keep their spelling, so hyphenated keys map straight onto long options, and flags follow the mapping’s iteration order.

Parameters:

table (Mapping[str, Any]) – The configuration keys and values, like a parsed [tool.X] section.

Return type:

list[str]

Returns:

The equivalent list of --flag / --flag=value arguments.

click_extra.config.ensure_config_loaded(ctx)[source]¶

Run the sibling ConfigOption’s resolution if it has not run yet.

Click processes eager parameters given on the command line before eager parameters left at their defaults, so an explicitly-passed introspection flag (--params, --export-config) fires before the --config option had a chance to discover and load the configuration file. The views those flags render would then miss the configuration layer entirely, showing defaults where the user’s config applies.

Idempotent: does nothing when the config option already resolved (its callback stamps CONF_SOURCE on the context even when no file was found), when the command has no config option, or when the option carries no callback.

Return type:

None

click_extra.config.field_docstrings(cls)[source]¶

Extract attribute docstrings from a class body, keyed by field name.

Attribute docstrings are string literals immediately following an annotated assignment in a class body (the PEP 257 convention used by Sphinx’s autodoc). Python discards them at runtime, so they are recovered by parsing the class source with ast. Each docstring is cleaned up with inspect.cleandoc(), preserving paragraph breaks.

Caution

Returns an empty mapping when the class source is unavailable, as for classes defined in an exec-ed code block (an interactive session, or the body of a click:source Sphinx directive). Import the schema from a real module to get its docstrings documented.

Return type:

dict[str, str]

click_extra.config.flatten_config_keys(conf, sep='_', opaque_keys=frozenset({}), _prefix='')[source]¶

Flatten nested dicts into a single level by joining keys with a separator.

Useful for mapping nested configuration structures (like TOML sub-tables) to flat Python dataclass fields. After normalization with normalize_config_keys, the flattened keys match dataclass field names directly:

>>> from click_extra.config import (
...     flatten_config_keys,
...     normalize_config_keys,
... )
>>> raw = {"dependency-graph": {"all-groups": True, "output": "deps.mmd"}}
>>> flatten_config_keys(normalize_config_keys(raw))
{'dependency_graph_all_groups': True, 'dependency_graph_output': 'deps.mmd'}
Parameters:
  • conf (dict[str, Any]) – Nested dictionary to flatten.

  • sep (str) – Separator used to join parent and child keys. Defaults to "_" which produces valid Python identifiers when combined with normalize_config_keys.

  • opaque_keys (frozenset[str]) – Fully-qualified key names where flattening stops. When the accumulated key matches an entry in this set, the dict value is kept as-is instead of being recursively flattened. This is useful for fields typed as dict[str, X] where the dict keys are data (like GitHub Actions matrix axis names), not config structure.

  • _prefix (str) – Internal parameter for tracking the accumulated key path during recursion. Callers should not set this.

Return type:

dict[str, Any]

click_extra.config.format_from_mime(mime_type, formats=None)[source]¶

Return the configuration format a media type designates.

The counterpart of format_from_path() for a configuration fetched over HTTP, whose URL often carries no usable file extension: the Content-Type header is then the only thing typing the payload. The media type is matched against each format’s mime_types, so application/toml resolves to TOML and text/yaml to YAML. formats restricts and orders the candidates (the first match wins); it defaults to every ConfigFormat.

Parameters are stripped, so a raw application/yaml; charset=utf-8 header value can be passed as-is, and matching is case-insensitive.

Note

A RFC 6839 structured syntax suffix is honored, so the application/vnd.acme.settings+json a private API answers with resolves to JSON. An exact match wins over a suffix.

Returns None for a media type no format claims, which covers the generic text/plain and application/octet-stream a server falls back to for an extension it does not recognize.

Return type:

ConfigFormat | None

click_extra.config.format_from_path(path, formats=None)[source]¶

Return the configuration format whose patterns match a file name.

The name is matched against each format’s patterns, so app.toml resolves to TOML and app.yml to YAML. formats restricts and orders the candidates (the first match wins); it defaults to every ConfigFormat.

Return type:

ConfigFormat | None

click_extra.config.get_tool_config(ctx=None)[source]¶

Retrieve the typed tool configuration from the context.

Returns the object stored under click_extra.context.TOOL_CONFIG by ConfigOption when a config_schema is set, or None if no schema was configured or no configuration was loaded.

Parameters:

ctx (Context | None) – Click context. Defaults to the current context.

Return type:

Any

click_extra.config.make_schema_callable(schema, *, strict=False, normalize=True, warn_unknown=False)[source]¶

Wrap a schema type into a callable that accepts a raw config dict.

  • Dataclass types (detected via dataclasses.is_dataclass) are auto-wrapped: keys are normalized (hyphens to underscores), nested dicts are flattened, and the result is filtered to known fields before instantiation. Three schema-aware features refine this process:

    1. Type-aware flattening. Fields typed as dict[str, X] are treated as opaque: flatten_config_keys stops at their boundary so the dict value is kept intact.

    2. Field metadata. Dataclass fields may carry click_extra.config_path (a dotted TOML path like "test-matrix.replace") and click_extra.normalize_keys (False to skip key normalization on the extracted value). Fields with an explicit path are extracted from the raw config before normalization and flattening.

    3. Nested dataclass support. Fields whose resolved type is itself a dataclass are recursively processed with the same logic.

  • Any other callable is returned as-is. The caller is responsible for key normalization if needed.

  • None returns None.

Parameters:
  • strict (bool) – If True, raise ValueError when the config contains keys that do not match any dataclass field (after normalization and flattening).

  • warn_unknown (bool) – If True (and strict is False), log a warning naming those same unknown keys instead of silently dropping them. Meant for configs whose section is schema-only (no CLI parameter is merged from it, i.e. included_params=()), where any unrecognized key can only be a typo. Applies recursively to nested dataclasses.

  • normalize (bool) – If False, skip normalize_config_keys on the remaining config dict. Used internally when recursing into nested dataclasses whose parent opted out of normalization via click_extra.normalize_keys = False.

Return type:

Callable[[dict[str, Any]], Any] | None

click_extra.config.normalize_config_keys(conf, opaque_keys=frozenset({}), _prefix='')[source]¶

Normalize configuration keys to valid Python identifiers.

Recursively replaces hyphens with underscores in all dict keys, using the same str.replace("-", "_") transform that Click applies internally when deriving parameter names from option declarations (--foo-bar becomes foo_bar).

Handles the convention mismatch between configuration formats (TOML, YAML, JSON all commonly use kebab-case) and Python identifiers. Works with all configuration formats supported by ConfigOption. A key that is not a string, like the number YAML reads 1: as, is kept as it is.

Parameters:
  • opaque_keys (frozenset[str]) – Fully-qualified key names (using "_" as separator) where recursion stops. The key itself is still normalized, but its dict value is kept as-is. Used in tandem with flatten_config_keys’s opaque_keys to protect data dicts (like GitHub Actions matrix axes) from normalization.

  • _prefix (str) – Internal parameter for tracking the accumulated key path during recursion. Callers should not set this.

Return type:

dict[str, Any]

Note

Click applies the same substitution in Option._parse_decls and Argument._parse_decls, but exposes no public accessor for it, so the one-liner is written out here.

click_extra.config.parse_content(fmt, content)[source]¶

Parse content with a single stateless format.

INI is excluded: it needs the CLI parameter structure for type coercion and is handled by load_ini_config(). ARGFILE is excluded for the same reason: it maps command-line tokens to the CLI’s parameters and is handled by load_argfile_config(). SQLITE is excluded too: it is a binary format, read from its file path by load_sqlite_config() instead of a text payload.

PLIST parses here from its XML variant, the only one expressible as a text payload. The binary variant is read from its file path by load_plist_config().

Note

Optional third-party parsers are imported at the point of use. Only enabled formats reach this function (disabled ones are filtered out of ConfigOption.file_format_patterns), so the import always resolves for the formats parsed here.

Return type:

Any

click_extra.config.read_file(path, formats=None)[source]¶

Read a file and parse it, picking the format from its name.

The format is resolved with format_from_path() over formats (every ConfigFormat by default), then the content is parsed with parse_content().

Raises:
  • ValueError – the file name matches none of the candidate formats.

  • ImportError – the matched format’s parser is not available.

Return type:

Any

click_extra.config.run_config_validation(user_conf, *, app_name, params_template, config_schema=None, config_validators=(), fallback_sections=(), schema_strict=False, schema_warn_unknown=False, strict=False, blocked_params=(), collect_all=True)[source]¶

Validate a parsed configuration document in one schema-driven pass.

Runs click-extra’s three checks (the CLI-parameter strict check, the dataclass schema, and the app-registered ConfigValidator hooks) behind a single function yielding a single error type. It is not named validate_config: that name belongs to validate_config(), the callback powering the --validate-config flag.

Stages, in order:

  1. Partition. Split opaque sub-trees (schema extension fields plus every registered validator’s extension_path) from the CLI-flag-bound content. Extracted sub-trees land in the report’s opaque_subtrees.

  2. Strict-check the CLI-flag-bound part against params_template, once its dotted keys are expanded, keeping the merged result as the report’s merged_conf (skipped when params_template is None). A key the dataclass schema reads is left to stage 3.

  3. Schema-build the app section through the configured callable, producing the report’s schema_instance.

  4. Validate every opaque sub-tree through its registered validator.

Parameters:
  • user_conf (dict[str, Any]) – The full parsed configuration document.

  • app_name (str) – Name of the app’s section (used to resolve the section and to root opaque paths and error paths at the document level).

  • params_template (dict[str, Any] | None) – The CLI-parameter template the strict check runs against. Pass None to skip the strict check entirely (for example, for a schema-only validation).

  • config_schema (type | Callable[[dict[str, Any]], Any] | None) – Dataclass type or callable describing the typed configuration, or None.

  • config_validators (Sequence[ConfigValidator]) – Extension validators to run against opaque sub-trees.

  • fallback_sections (Sequence[str]) – Legacy section names to try when app_name is absent or empty.

  • schema_strict (bool) – Reject keys the dataclass schema does not recognize.

  • schema_warn_unknown (bool) – In lax mode, log a warning naming keys the dataclass schema does not recognize (see warn_unknown in make_schema_callable()). Ignored when schema_strict rejects them outright.

  • strict (bool) – Reject keys that neither the CLI-parameter template nor the dataclass schema recognize, keys that are not strings, and dotted keys that conflict with another key or have an empty segment.

  • blocked_params (Iterable[str]) – Fully-qualified IDs of parameters excluded from configuration files, used to sharpen strict-mode error messages (a blocked parameter is reported as such, not as unknown).

  • collect_all (bool) – When True (default), run every stage and collect all errors. When False, the first error short-circuits the rest.

Return type:

ValidationReport

Returns:

A ValidationReport. ValidationError is the single error type recorded by every stage; a ValueError or TypeError raised by the schema callable is wrapped into it.

click_extra.config.schema_field_infos(schema)[source]¶

Walk a configuration schema dataclass into per-option records.

Introspects the dataclass fields, their type annotations, defaults, and attribute docstrings. Nested dataclass fields expand recursively into dotted keys (test-suite.timeout), honoring click_extra.config.schema.CONFIG_PATH_METADATA_KEY at every level. Records are sorted by key, segment-wise, so a sub-table’s options stay contiguous even when another table’s name shares their prefix (workflow.sync sorts before workflow-pins.sync).

Defaults are read off a pristine schema() instance, so every field must carry a default: configuration schemas are default-complete by construction, since make_schema_callable() instantiates them from partial user data.

Raises:

TypeError – when schema is not a dataclass type.

Return type:

list[SchemaFieldInfo]

click_extra.config.serialize_content(fmt, data, **kwargs)[source]¶

Serialize a Python object to a string in the given format.

The dumping counterpart to parse_content(). Per-format defaults can be overridden through kwargs (forwarded to the underlying serializer). JSON5 and JSONC are emitted as plain JSON, a valid subset of both.

Caution

Not every format round-trips: TOML, XML and PLIST have no null type (plistlib even raises on None values), and XML expects a single root mapping, so the caller is responsible for shaping data accordingly. INI, SQLITE, ARGFILE and PYPROJECT_TOML have no serializer.

Note

Optional third-party serializers are imported lazily, at the point of use. Writing TOML uses tomlrt (the [toml] extra), unlike reading which relies on the built-in tomllib.

Raises:

ValueError – the format has no serializer.

Return type:

str

Submodules¶

click_extra.config.builtin module¶

Click Extra’s own built-in configuration schema.

The dataclasses describing click-extra’s own [tool.click-extra] section: ClickExtraConfig and its test-suite and prebake sub-tables. They are a concrete instance of the configuration machinery, kept apart from the reusable engine in schema and the option classes in option. Only the click-extra CLI reads them, so import click_extra does not load this module.

A downstream project defines its own equivalent of this module; click-extra just happens to ship one, built on the same generic engine.

class click_extra.config.builtin.TestSuiteConfig(file='./tests/cli-test-suite.toml', cases=list(), timeout=None)[source]¶

Bases: object

Config schema for a project’s test suite, read from [tool.<cli>.test-suite].

The test-suite CLI command resolves its cases from this config when no suite is given on the command line. Map it onto an app’s config section with a field carrying metadata={CONFIG_PATH_METADATA_KEY: "test-suite"}.

file: str = './tests/cli-test-suite.toml'¶

Path to a test suite file, resolved relative to the project root.

Its format is detected from the extension; the default is TOML, which (like JSON) parses with no optional dependency, unlike YAML and the others.

cases: list[dict]¶

Test cases written natively in the config format, an alternative to a file suite, taking precedence over it when both are set.

Each entry is a mapping of CLITestCase directive names, equivalent to one item of a suite list. In TOML this reads as a [[tool.<cli>.test-suite.cases]] array of tables. Declared as an extension point so the configuration engine passes the raw mappings through unprocessed; the test-suite command turns them into CLITestCase instances.

timeout: int | None = None¶

Default timeout (seconds) for each case that does not set its own.

None leaves cases unbounded unless --timeout is passed.

class click_extra.config.builtin.PrebakeConfig(module=None)[source]¶

Bases: object

Config schema for the prebake commands, read from [tool.<cli>.prebake].

Lets a project pin the target __init__.py once for its build pipeline, instead of passing --module to every click-extra prebake command.

module: str | None = None¶

Path to the __init__.py to pre-bake, resolved relative to the project root. Overrides the [project.scripts] auto-discovery; leave unset to keep it.

class click_extra.config.builtin.ClickExtraConfig(test_suite=TestSuiteConfig(), prebake=PrebakeConfig())[source]¶

Bases: object

Schema for the [tool.click-extra] configuration section.

Wired as the config_schema of the top-level click-extra group, so every subcommand reads the same section and pulls its own sub-table through get_tool_config().

test_suite: TestSuiteConfig¶

The [tool.click-extra.test-suite] sub-table (file/cases/timeout).

prebake: PrebakeConfig¶

The [tool.click-extra.prebake] sub-table (target module).

click_extra.config.discovery module¶

Search for the configuration files a --config location designates.

ConfigDiscovery is the mixin ConfigOption inherits to find its files. It downloads a URL, or globs a local pattern, then walks up the parent folders until a VCS root. It also looks for a pyproject.toml from the current working directory upward.

click_extra.config.discovery.VCS_DIRS = ('.git', '.hg', '.svn', '.bzr', 'CVS', '.darcs')¶

VCS directory names used to identify version control system roots.

Includes: - .git: Git - .hg: Mercurial - .svn: Subversion - .bzr: Bazaar - CVS: CVS (note: uppercase, no leading dot) - .darcs: Darcs

class click_extra.config.discovery.ConfigDiscovery[source]¶

Bases: object

Find the configuration files a location designates.

A mixin of ConfigOption, which sets the attributes the search reads: search_pattern_flags, search_parents and stop_at. A pyproject.toml is read with the option’s own parse_conf().

search_parents: bool¶
stop_at: Path | str | Literal[Sentinel.VCS] | None¶
parent_patterns(pattern)[source]¶

Generate (root_dir, file_pattern) pairs for searching.

Each yielded pair can be passed directly to glob.iglob(file_pattern, root_dir=root_dir) so that every sub-pattern (whether from BRACE or SPLIT expansion) is correctly scoped to the same directory.

root_dir is None for entirely magic patterns that will be evaluated relative to the current working directory.

Stops when reaching the root folder, the stop_at boundary, or an inaccessible directory.

Return type:

Iterable[tuple[str | None, str]]

search_and_read_file(pattern)[source]¶

Search filesystem or URL for files matching the pattern.

If pattern is an URL, download its content. A pattern is considered an URL only if it validates as one and starts with http:// or https://. All other patterns are considered glob patterns for local filesystem search.

Returns an iterator of (location, content, media_type) triples, for each one matching the pattern. location is normalized and content raw. media_type is the bare type/subtype the server advertised in its Content-Type header, and is None for a local file, whose format is derived from its name. Only regular files are returned, directories are silently skipped. The exception is a pattern naming a character device or a named pipe, like /dev/null: it is read from that path.

This method returns the raw content of all matching patterns, without trying to parse them. If the content is empty, it is still returned as-is.

Also includes lookups into parents directories if self.search_parents is True.

Raises FileNotFoundError if no file was found after searching all locations.

Return type:

Iterable[tuple[Path | str, str, str | None]]

click_extra.config.export module¶

Export the resolved configuration of a CLI as a configuration file.

Holds ExportConfigOption, the --export-config FORMAT option, and ensure_config_loaded(), which loads the configuration ahead of the introspection flags that read it.

click_extra.config.export.ensure_config_loaded(ctx)[source]¶

Run the sibling ConfigOption’s resolution if it has not run yet.

Click processes eager parameters given on the command line before eager parameters left at their defaults, so an explicitly-passed introspection flag (--params, --export-config) fires before the --config option had a chance to discover and load the configuration file. The views those flags render would then miss the configuration layer entirely, showing defaults where the user’s config applies.

Idempotent: does nothing when the config option already resolved (its callback stamps CONF_SOURCE on the context even when no file was found), when the command has no config option, or when the option carries no callback.

Return type:

None

class click_extra.config.export.ExportConfigOption(param_decls=None, *, type=None, metavar='FORMAT', is_eager=True, expose_value=False, help='Export the configuration in the selected format to <stdout>, then exit.', **kwargs)[source]¶

Bases: ExtraOption

A pre-configured option adding --export-config FORMAT.

Resolves the CLI’s current parameter values following Click’s precedence chain (command line, then environment variables, then configuration file, then defaults), renders them as a configuration file in the requested format on <stdout>, and exits.

Hint

Combine the flag with other options or environment variables to capture them in the generated configuration. For example, mycli --verbosity DEBUG --export-config toml emits a configuration whose verbosity is already set to DEBUG.

Like ValidateConfigOption, it relies on a sibling ConfigOption to provide the parameter structure and the excluded_params / included_params filter, so the export contains exactly the parameters that can be loaded back from a configuration file.

Note

The accepted formats are those serialize_content() can write (SERIALIZABLE_FORMATS). INI, SQLITE, ARGFILE and PYPROJECT_TOML have no serializer and cannot be dumped.

build_config(ctx, config_option)[source]¶

Resolve every config-eligible parameter into a dumpable tree.

Walks the sibling ConfigOption’s parameter structure, resolves each parameter’s effective value by replaying RAW_ARGS (falling back to defaults when the command did not capture them), drops the parameters is_excluded() rejects, and layers the coerced values into the {cli-name: {param: value, ...}} shape a configuration file uses. Parameter keys are rendered in their kebab-case spelling, the canonical presentation for configuration files; either spelling loads back to the same parameter.

Parameters without a default are kept as None leaves so the export names every key a configuration file can set: serializers render them as null, except TOML which comments them out (see _serialize_toml_with_unset). Loading null back is harmless: _install_default_map() cleans blank values out of the merged result.

Return type:

dict[str, Any]

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

Render the resolved configuration to <stdout> and exit.

Return type:

None

click_extra.config.flags module¶

Translate a configuration table into command-line flags.

click_extra.config.flags.config_table_to_flags(table)[source]¶

Translate a mapping of configuration keys into long-form CLI flags.

For tools whose command-line options mirror their configuration keys but which cannot read the table themselves (no --config support, no native config file). Follows the conventional mapping:

  • key = True → --key

  • key = "value" (or a number) → --key=value

  • key = ["a", "b"] → --key=a --key=b (one flag per item)

  • key = False is skipped: there is no universal --no-<key> form.

Keys keep their spelling, so hyphenated keys map straight onto long options, and flags follow the mapping’s iteration order.

Parameters:

table (Mapping[str, Any]) – The configuration keys and values, like a parsed [tool.X] section.

Return type:

list[str]

Returns:

The equivalent list of --flag / --flag=value arguments.

click_extra.config.formats module¶

Configuration file formats and their stateless content parsers.

Holds the ConfigFormat enum, which probes on first use the modules that decide whether a format is enabled, and parse_content(), the stateless dispatch used by ConfigOption for every format that does not need the CLI parameter structure.

Caution

This module is imported early in the package’s import graph (table reaches it before the parameters / context chain has settled), so it takes no top-level import from click_extra itself. A format whose parsing needs the CLI structure or a binary file, like INI, ARGFILE and SQLITE, lives as a ConfigOption method in option instead of here.

class click_extra.config.formats.ConfigFormat(*values)[source]¶

Bases: Enum

All configuration formats, associated to their support status.

Each member’s value is a tuple of four elements:

  1. The file patterns associated to the format. Patterns are fed to wcmatch.glob for matching, and are influenced by the flags set on the ConfigOption instance.

  2. The module backing the format, or None for a format the interpreter always supports. enabled probes it on first use.

  3. The human-readable label of the format.

  4. The media types a server may serve it as, as matched by format_from_mime().

Caution

The order is important for both format members and file patterns. It defines the priority order in which formats are tried when multiple candidate files are found.

TOML = (('*.toml',), None, 'TOML', ('application/toml', 'text/x-toml'))¶
YAML = (('*.yaml', '*.yml'), 'yaml', 'YAML', ('application/yaml', 'text/yaml', 'application/x-yaml', 'text/x-yaml'))¶
JSON = (('*.json',), None, 'JSON', ('application/json', 'text/json'))¶
JSON5 = (('*.json5', '*.jwcc'), 'json5', 'JSON5', ('application/json5',))¶
JSONC = (('*.jsonc',), None, 'JSONC', ('application/jsonc',))¶
HJSON = (('*.hjson',), 'hjson', 'Hjson', ('application/hjson',))¶
INI = (('*.ini',), None, 'INI', ())¶
XML = (('*.xml',), None, 'XML', ('application/xml', 'text/xml'))¶
PLIST = (('*.plist',), None, 'plist', ('application/x-plist',))¶
SQLITE = (('*.sqlite', '*.sqlite3'), '_sqlite3', 'SQLite', ('application/vnd.sqlite3', 'application/x-sqlite3'))¶
ARGFILE = (('*.conf',), None, 'Argfile', ())¶
PYPROJECT_TOML = (('pyproject.toml',), None, 'pyproject.toml', ())¶
property label: str¶

Human-friendly name of the format for display in messages.

property enabled: bool¶

Whether the module backing the format is available.

The module is probed on the first read, without being imported, and the answer is cached for the life of the process. Importing click_extra probes nothing: the first ConfigOption built does.

property patterns: tuple[str, ...]¶

Returns the default file patterns associated to the format.

property mime_types: tuple[str, ...]¶

Media types a server may advertise the format as.

Feeds format_from_mime(). Empty for a format no Content-Type header designates: INI and ARGFILE are both served as text/plain, which names no format, and PYPROJECT_TOML is keyed on a file name, so no media type tells it apart from plain TOML.

click_extra.config.formats.SQLITE_CONFIG_TABLE = 'config'¶

Name of the table click_extra.config.option.ConfigOption.load_sqlite_config() reads a SQLITE configuration from.

The table holds key/value columns: dotted parameter paths and their JSON-encoded values.

click_extra.config.formats.parse_jsonc(content)[source]¶

Read a JSONC document: JSON with comments and trailing commas.

The comments are blanked and the trailing commas removed before json reads the rest, so an error it raises still names the line it sits on. A string keeps its content whole: a // or a comma inside it is not syntax.

Return type:

Any

click_extra.config.formats.parse_xml(content)[source]¶

Read an XML document into nested dictionaries, the root element outermost.

An element holding text alone reads as that text, stripped of the whitespace around it, or as None when there is none. One holding attributes or child elements reads as a dictionary: an attribute under its name prefixed with @, a child under its tag, and the text under #text. Elements repeating a tag under the same parent are collected into a list, in document order. Comments and processing instructions are skipped, and a tag keeps its namespace prefix as written. These are the conventions of xmltodict.

Raises:

xml.parsers.expat.ExpatError – on a malformed document.

Return type:

dict[str, Any]

click_extra.config.formats.serialize_xml(data, *, indent='\t')[source]¶

Write nested dictionaries as an XML document, one element per level.

The inverse of parse_xml(), with the same conventions: a @ key is an attribute, #text the text of an element that also carries attributes or children, a list a run of elements sharing a tag, and None or an empty string an empty element. Each top-level key is a root element. Child elements sit on their own lines, each level pushed by one indent. A key XML does not accept as a name is respelled, like 0 into _0 and my key into my_key, so the document stays well-formed.

Return type:

str

click_extra.config.formats.parse_content(fmt, content)[source]¶

Parse content with a single stateless format.

INI is excluded: it needs the CLI parameter structure for type coercion and is handled by load_ini_config(). ARGFILE is excluded for the same reason: it maps command-line tokens to the CLI’s parameters and is handled by load_argfile_config(). SQLITE is excluded too: it is a binary format, read from its file path by load_sqlite_config() instead of a text payload.

PLIST parses here from its XML variant, the only one expressible as a text payload. The binary variant is read from its file path by load_plist_config().

Note

Optional third-party parsers are imported at the point of use. Only enabled formats reach this function (disabled ones are filtered out of ConfigOption.file_format_patterns), so the import always resolves for the formats parsed here.

Return type:

Any

click_extra.config.formats.SERIALIZABLE_FORMATS: tuple[ConfigFormat, ...] = (ConfigFormat.TOML, ConfigFormat.YAML, ConfigFormat.JSON, ConfigFormat.JSON5, ConfigFormat.JSONC, ConfigFormat.HJSON, ConfigFormat.XML, ConfigFormat.PLIST)¶

Configuration formats serialize_content() can write, in priority order.

Every ConfigFormat except INI, SQLITE, ARGFILE and PYPROJECT_TOML, which have no serializer. JSON, JSON5 and JSONC are emitted as plain JSON and PLIST through plistlib, all from the standard library, so they need no optional dependency; the others require their format’s extra.

Caution

Keep this in sync with the match statement in serialize_content().

click_extra.config.formats.serialize_content(fmt, data, **kwargs)[source]¶

Serialize a Python object to a string in the given format.

The dumping counterpart to parse_content(). Per-format defaults can be overridden through kwargs (forwarded to the underlying serializer). JSON5 and JSONC are emitted as plain JSON, a valid subset of both.

Caution

Not every format round-trips: TOML, XML and PLIST have no null type (plistlib even raises on None values), and XML expects a single root mapping, so the caller is responsible for shaping data accordingly. INI, SQLITE, ARGFILE and PYPROJECT_TOML have no serializer.

Note

Optional third-party serializers are imported lazily, at the point of use. Writing TOML uses tomlrt (the [toml] extra), unlike reading which relies on the built-in tomllib.

Raises:

ValueError – the format has no serializer.

Return type:

str

click_extra.config.formats.format_from_path(path, formats=None)[source]¶

Return the configuration format whose patterns match a file name.

The name is matched against each format’s patterns, so app.toml resolves to TOML and app.yml to YAML. formats restricts and orders the candidates (the first match wins); it defaults to every ConfigFormat.

Return type:

ConfigFormat | None

click_extra.config.formats.format_from_mime(mime_type, formats=None)[source]¶

Return the configuration format a media type designates.

The counterpart of format_from_path() for a configuration fetched over HTTP, whose URL often carries no usable file extension: the Content-Type header is then the only thing typing the payload. The media type is matched against each format’s mime_types, so application/toml resolves to TOML and text/yaml to YAML. formats restricts and orders the candidates (the first match wins); it defaults to every ConfigFormat.

Parameters are stripped, so a raw application/yaml; charset=utf-8 header value can be passed as-is, and matching is case-insensitive.

Note

A RFC 6839 structured syntax suffix is honored, so the application/vnd.acme.settings+json a private API answers with resolves to JSON. An exact match wins over a suffix.

Returns None for a media type no format claims, which covers the generic text/plain and application/octet-stream a server falls back to for an extension it does not recognize.

Return type:

ConfigFormat | None

click_extra.config.formats.disabled_format_message(fmt)[source]¶

Build the “format support disabled” message for a format.

The single source for the debug line logged when ConfigFormat.enabled finds the parser missing, and for the ImportError text raised when such a format is requested, shared by read_file() and click_extra.test_suite.parse_test_suite(). A format’s label, lower-cased, is its click-extra[<extra>] install target, worded like every other missing optional dependency of the package.

SQLITE is the exception: it reads through the standard library, so no extra installs it and it gets _NO_SQLITE_MESSAGE instead.

Return type:

str

click_extra.config.formats.read_file(path, formats=None)[source]¶

Read a file and parse it, picking the format from its name.

The format is resolved with format_from_path() over formats (every ConfigFormat by default), then the content is parsed with parse_content().

Raises:
  • ValueError – the file name matches none of the candidate formats.

  • ImportError – the matched format’s parser is not available.

Return type:

Any

click_extra.config.option module¶

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

click_extra.config.schema module¶

Schema-building and validation engine behind config_option and –validate-config.

click_extra.config.schema.DEFAULT_SUBCOMMANDS_KEY = '_default_subcommands'¶

Reserved configuration key for specifying default subcommands.

When a group is invoked without explicit subcommands on the CLI, the subcommands listed under this key execute automatically in order. CLI always wins: if the user names subcommands explicitly, the config is ignored.

Example TOML configuration:

[my-cli]
_default_subcommands = ["backup", "sync"]

[my-cli.backup]
path = "/home"
click_extra.config.schema.PREPEND_SUBCOMMANDS_KEY = '_prepend_subcommands'¶

Reserved configuration key for prepending subcommands to every invocation.

Unlike _default_subcommands which only fires when no subcommands are given on the CLI, _prepend_subcommands always prepends the listed subcommands. This is useful for always injecting a debug subcommand on a dev machine, for example.

Only works with chain=True groups (non-chained groups resolve exactly one subcommand, so prepending would break the user’s intended command).

Example TOML configuration:

[my-cli]
_prepend_subcommands = ["debug"]
click_extra.config.schema.EXTENSION_METADATA_KEY = 'click_extra.extension'¶

Dataclass field metadata flag marking a field as an extension point.

Schema authors set metadata={EXTENSION_METADATA_KEY: True} on a field when its sub-tree should pass through click-extra’s CLI-parameter strict check and be validated by app-specific logic instead. Equivalent to typing the field as dict[str, X]: both forms are recognized by _collect_opaque_paths_from_schema (the internal pipeline calls these paths opaque, as its normalize, flatten and strict stages skip them). The metadata form is useful when the underlying Python type is something other than a dict (for example, a nested dataclass that represents user-extensible content).

click_extra.config.schema.CONFIG_PATH_METADATA_KEY = 'click_extra.config_path'¶

Dataclass field metadata key pinning a field to an explicit config sub-path.

Schema authors set metadata={CONFIG_PATH_METADATA_KEY: "test-suite"} on a field so the dataclass loader (_from_dataclass) reads its value from that dotted path under the app’s configuration section, rather than from a key named after the field. The named counterpart to EXTENSION_METADATA_KEY.

click_extra.config.schema.NORMALIZE_KEYS_METADATA_KEY = 'click_extra.normalize_keys'¶

Dataclass field metadata key toggling key normalization on a field’s value.

Defaults to True. Schema authors set metadata={NORMALIZE_KEYS_METADATA_KEY: False} to keep a sub-tree’s keys verbatim, so external identifiers (like python-version axis names) are not rewritten to Python-style names (python_version). Read by _from_dataclass alongside CONFIG_PATH_METADATA_KEY.

exception click_extra.config.schema.ValidationError(path, message, code=None)[source]¶

Bases: ValueError

Raised when a configuration file fails validation.

A single, structured exception type that uniformly carries the dotted path of the offending key, a human-readable message, and an optional code for programmatic handling. Used by click-extra’s built-in strict-mode check and by every user-registered ConfigValidator, so downstream apps and --validate-config see the same error shape regardless of who detected the problem.

Click-extra raises it with one of these codes, all spelled in snake case:

  • invalid_key: a dotted key conflicts with another key, or has an empty segment, or a key is not a string.

  • invalid_theme: a [tool.<cli>.themes.<name>] table builds no theme, like one naming a slot no theme has.

  • invalid_theme_shape: a [tool.<cli>.themes.<name>] entry is not a table.

  • schema_error: the configuration schema rejects the section.

  • unknown_parameter: a key matches no CLI parameter, or one excluded from configuration files.

Parameters:
  • path (str) – Dotted path to the offending key, relative to the configuration file root (like "my-cli.managers.winget.cli_searchpath"). An empty string means the error applies to the document as a whole.

  • message (str) – Human-readable description of the failure. Should be a single sentence, no trailing punctuation, no path repeated.

  • code (str | None) – Optional machine-readable error code (like "unknown_field") for callers that want to dispatch on error type without parsing the message string.

class click_extra.config.schema.ConfigValidator(extension_path, validator, description='')[source]¶

Bases: object

Register an app-defined extension validator for one sub-tree of the configuration file.

Apps register validators via the config_validators= kwarg on ConfigOption (or the matching decorator) to extend click-extra’s built-in CLI-parameter strict check with custom validation logic. Each validator targets a single dotted extension_path relative to the app’s configuration section. Click-extra passes the matching sub-tree straight through to the registered validator: the strict check skips it, the schema machinery treats it as opaque, and the user’s logic owns the result. The validator runs both during --validate-config and during normal config loading.

Parameters:
  • extension_path (str) – Dotted path of the sub-tree the validator owns, relative to the app’s section in the configuration file. For example, an app named my-cli with extension_path="managers" receives the contents of the [my-cli.managers] table.

  • validator (Callable[[dict[str, Any]], None]) – Callable taking the sub-tree dict and raising ValidationError on failure. Must be a pure function: no side effects on the click context, no print statements. The caller decides how to surface the error.

  • description (str) – Optional human-readable summary of what the validator checks, for documentation generators that introspect the registration.

extension_path: str¶
validator: Callable[[dict[str, Any]], None]¶
description: str = ''¶
click_extra.config.schema.normalize_config_keys(conf, opaque_keys=frozenset({}), _prefix='')[source]¶

Normalize configuration keys to valid Python identifiers.

Recursively replaces hyphens with underscores in all dict keys, using the same str.replace("-", "_") transform that Click applies internally when deriving parameter names from option declarations (--foo-bar becomes foo_bar).

Handles the convention mismatch between configuration formats (TOML, YAML, JSON all commonly use kebab-case) and Python identifiers. Works with all configuration formats supported by ConfigOption. A key that is not a string, like the number YAML reads 1: as, is kept as it is.

Parameters:
  • opaque_keys (frozenset[str]) – Fully-qualified key names (using "_" as separator) where recursion stops. The key itself is still normalized, but its dict value is kept as-is. Used in tandem with flatten_config_keys’s opaque_keys to protect data dicts (like GitHub Actions matrix axes) from normalization.

  • _prefix (str) – Internal parameter for tracking the accumulated key path during recursion. Callers should not set this.

Return type:

dict[str, Any]

Note

Click applies the same substitution in Option._parse_decls and Argument._parse_decls, but exposes no public accessor for it, so the one-liner is written out here.

click_extra.config.schema.flatten_config_keys(conf, sep='_', opaque_keys=frozenset({}), _prefix='')[source]¶

Flatten nested dicts into a single level by joining keys with a separator.

Useful for mapping nested configuration structures (like TOML sub-tables) to flat Python dataclass fields. After normalization with normalize_config_keys, the flattened keys match dataclass field names directly:

>>> from click_extra.config import (
...     flatten_config_keys,
...     normalize_config_keys,
... )
>>> raw = {"dependency-graph": {"all-groups": True, "output": "deps.mmd"}}
>>> flatten_config_keys(normalize_config_keys(raw))
{'dependency_graph_all_groups': True, 'dependency_graph_output': 'deps.mmd'}
Parameters:
  • conf (dict[str, Any]) – Nested dictionary to flatten.

  • sep (str) – Separator used to join parent and child keys. Defaults to "_" which produces valid Python identifiers when combined with normalize_config_keys.

  • opaque_keys (frozenset[str]) – Fully-qualified key names where flattening stops. When the accumulated key matches an entry in this set, the dict value is kept as-is instead of being recursively flattened. This is useful for fields typed as dict[str, X] where the dict keys are data (like GitHub Actions matrix axis names), not config structure.

  • _prefix (str) – Internal parameter for tracking the accumulated key path during recursion. Callers should not set this.

Return type:

dict[str, Any]

click_extra.config.schema.get_tool_config(ctx=None)[source]¶

Retrieve the typed tool configuration from the context.

Returns the object stored under click_extra.context.TOOL_CONFIG by ConfigOption when a config_schema is set, or None if no schema was configured or no configuration was loaded.

Parameters:

ctx (Context | None) – Click context. Defaults to the current context.

Return type:

Any

class click_extra.config.schema.SchemaFieldInfo(key, type_hint, default, summary, description)[source]¶

Bases: NamedTuple

Documentation record for one option of a configuration schema.

Produced by schema_field_infos(). Consumed by the click:config Sphinx directive, and by CLIs building their own configuration reference (a show-config table, say) from the same introspection.

Create new instance of SchemaFieldInfo(key, type_hint, default, summary, description)

key: str¶

Dotted configuration path of the option.

Field names are kebab-cased (setup_guide → setup-guide) unless the field pins an explicit path through click_extra.config.schema.CONFIG_PATH_METADATA_KEY. Nested dataclass fields contribute one segment per nesting level (test-suite.timeout).

type_hint: str¶

The field’s type annotation, as written in the schema source.

default: Any¶

The field’s default value, taken from a pristine schema instance.

summary: str¶

First paragraph of the field’s attribute docstring, collapsed onto a single line. Empty when the field has no docstring or the class source is unavailable (see field_docstrings()).

description: str¶

Full attribute docstring of the field, paragraph breaks preserved.

click_extra.config.schema.field_docstrings(cls)[source]¶

Extract attribute docstrings from a class body, keyed by field name.

Attribute docstrings are string literals immediately following an annotated assignment in a class body (the PEP 257 convention used by Sphinx’s autodoc). Python discards them at runtime, so they are recovered by parsing the class source with ast. Each docstring is cleaned up with inspect.cleandoc(), preserving paragraph breaks.

Caution

Returns an empty mapping when the class source is unavailable, as for classes defined in an exec-ed code block (an interactive session, or the body of a click:source Sphinx directive). Import the schema from a real module to get its docstrings documented.

Return type:

dict[str, str]

click_extra.config.schema.schema_field_infos(schema)[source]¶

Walk a configuration schema dataclass into per-option records.

Introspects the dataclass fields, their type annotations, defaults, and attribute docstrings. Nested dataclass fields expand recursively into dotted keys (test-suite.timeout), honoring click_extra.config.schema.CONFIG_PATH_METADATA_KEY at every level. Records are sorted by key, segment-wise, so a sub-table’s options stay contiguous even when another table’s name shares their prefix (workflow.sync sorts before workflow-pins.sync).

Defaults are read off a pristine schema() instance, so every field must carry a default: configuration schemas are default-complete by construction, since make_schema_callable() instantiates them from partial user data.

Raises:

TypeError – when schema is not a dataclass type.

Return type:

list[SchemaFieldInfo]

click_extra.config.schema.make_schema_callable(schema, *, strict=False, normalize=True, warn_unknown=False)[source]¶

Wrap a schema type into a callable that accepts a raw config dict.

  • Dataclass types (detected via dataclasses.is_dataclass) are auto-wrapped: keys are normalized (hyphens to underscores), nested dicts are flattened, and the result is filtered to known fields before instantiation. Three schema-aware features refine this process:

    1. Type-aware flattening. Fields typed as dict[str, X] are treated as opaque: flatten_config_keys stops at their boundary so the dict value is kept intact.

    2. Field metadata. Dataclass fields may carry click_extra.config_path (a dotted TOML path like "test-matrix.replace") and click_extra.normalize_keys (False to skip key normalization on the extracted value). Fields with an explicit path are extracted from the raw config before normalization and flattening.

    3. Nested dataclass support. Fields whose resolved type is itself a dataclass are recursively processed with the same logic.

  • Any other callable is returned as-is. The caller is responsible for key normalization if needed.

  • None returns None.

Parameters:
  • strict (bool) – If True, raise ValueError when the config contains keys that do not match any dataclass field (after normalization and flattening).

  • warn_unknown (bool) – If True (and strict is False), log a warning naming those same unknown keys instead of silently dropping them. Meant for configs whose section is schema-only (no CLI parameter is merged from it, i.e. included_params=()), where any unrecognized key can only be a typo. Applies recursively to nested dataclasses.

  • normalize (bool) – If False, skip normalize_config_keys on the remaining config dict. Used internally when recursing into nested dataclasses whose parent opted out of normalization via click_extra.normalize_keys = False.

Return type:

Callable[[dict[str, Any]], Any] | None

class click_extra.config.schema.ValidationReport(schema_instance, opaque_subtrees, errors, merged_conf=None)[source]¶

Bases: object

Outcome of one pass through run_config_validation().

Bundles everything a caller needs after validating a parsed configuration document: the typed schema instance, the extracted opaque sub-trees, the template-filtered config ready for default_map, and every error detected across all validation stages.

Note

The report holds references to the parsed sub-trees, not copies, so building it is cheap regardless of document size.

schema_instance: Any | None¶

Typed object produced by the configured schema callable.

None when no schema is configured, or when the schema stage raised (in which case the failure is recorded in errors).

opaque_subtrees: dict[str, dict[str, Any]]¶

Extracted extension sub-trees, keyed by dotted path relative to the app section. Only paths actually present in the document appear here, so callers can re-route them to per-path validators or stash them on ctx.meta.

errors: tuple[ValidationError, ...]¶

Every ValidationError detected, in stage order (CLI-flag keys first, then schema errors, then validator failures). Empty on success.

With collect_all=False this holds at most one error: the first failure short-circuits the remaining stages.

merged_conf: dict[str, Any] | None = None¶

The CLI-flag-bound configuration merged onto params_template: the payload load_conf() layers into the context’s default_map, as merge_default_map() does.

None when params_template was None (no strict check) or the strict check failed.

property ok: bool¶

True when no error was detected.

click_extra.config.schema.run_config_validation(user_conf, *, app_name, params_template, config_schema=None, config_validators=(), fallback_sections=(), schema_strict=False, schema_warn_unknown=False, strict=False, blocked_params=(), collect_all=True)[source]¶

Validate a parsed configuration document in one schema-driven pass.

Runs click-extra’s three checks (the CLI-parameter strict check, the dataclass schema, and the app-registered ConfigValidator hooks) behind a single function yielding a single error type. It is not named validate_config: that name belongs to validate_config(), the callback powering the --validate-config flag.

Stages, in order:

  1. Partition. Split opaque sub-trees (schema extension fields plus every registered validator’s extension_path) from the CLI-flag-bound content. Extracted sub-trees land in the report’s opaque_subtrees.

  2. Strict-check the CLI-flag-bound part against params_template, once its dotted keys are expanded, keeping the merged result as the report’s merged_conf (skipped when params_template is None). A key the dataclass schema reads is left to stage 3.

  3. Schema-build the app section through the configured callable, producing the report’s schema_instance.

  4. Validate every opaque sub-tree through its registered validator.

Parameters:
  • user_conf (dict[str, Any]) – The full parsed configuration document.

  • app_name (str) – Name of the app’s section (used to resolve the section and to root opaque paths and error paths at the document level).

  • params_template (dict[str, Any] | None) – The CLI-parameter template the strict check runs against. Pass None to skip the strict check entirely (for example, for a schema-only validation).

  • config_schema (type | Callable[[dict[str, Any]], Any] | None) – Dataclass type or callable describing the typed configuration, or None.

  • config_validators (Sequence[ConfigValidator]) – Extension validators to run against opaque sub-trees.

  • fallback_sections (Sequence[str]) – Legacy section names to try when app_name is absent or empty.

  • schema_strict (bool) – Reject keys the dataclass schema does not recognize.

  • schema_warn_unknown (bool) – In lax mode, log a warning naming keys the dataclass schema does not recognize (see warn_unknown in make_schema_callable()). Ignored when schema_strict rejects them outright.

  • strict (bool) – Reject keys that neither the CLI-parameter template nor the dataclass schema recognize, keys that are not strings, and dotted keys that conflict with another key or have an empty segment.

  • blocked_params (Iterable[str]) – Fully-qualified IDs of parameters excluded from configuration files, used to sharpen strict-mode error messages (a blocked parameter is reported as such, not as unknown).

  • collect_all (bool) – When True (default), run every stage and collect all errors. When False, the first error short-circuits the rest.

Return type:

ValidationReport

Returns:

A ValidationReport. ValidationError is the single error type recorded by every stage; a ValueError or TypeError raised by the schema callable is wrapped into it.

click_extra.config.subcommands module¶

Resolution of the reserved subcommand keys a configuration file can declare.

_default_subcommands and _prepend_subcommands are read from the loaded configuration and turned into subcommand names, which handle_parse_result() splices into the residual arguments Click dispatches on.

Note

The keys are honored by whichever group carries the --config option, not only by click-extra’s own Group. Injection happens at parse time, from the option itself, because a plain click.Group offers click-extra no other hook: a third-party framework building its group on click.Group still gets the feature.

Caution

The option never sees two cases. Click prints the no_args_is_help screen of a bare invocation before it processes any option, and a group reached through an ancestor’s --config carries no option of its own. The first ConfigOption a process builds puts _group_parse_args() in place of click.Group.parse_args for the whole process to cover both, whatever class the group is built on: see its documentation.

click_extra.config.subcommands.resolve_default_subcommands(ctx, group)[source]¶

Read and validate _default_subcommands from the loaded configuration.

Return type:

list[str] | None

click_extra.config.subcommands.resolve_prepend_subcommands(ctx, group)[source]¶

Read and validate _prepend_subcommands from the loaded configuration.

Return type:

list[str] | None

click_extra.config.subcommands.inject_reserved_subcommands(ctx, args)[source]¶

Return args with the reserved subcommand keys applied.

_default_subcommands fills in for an invocation that names no subcommand. The command line always wins: when args already carries one, the configured defaults are logged and dropped.

_prepend_subcommands goes in front of whatever remains, whether the subcommand came from the command line or from the defaults. It requires a chain=True group.

Applies at most once per group, tracked in SUBCOMMANDS_APPLIED. A group can be visited twice, by the pre-pass of a bare invocation and then by the regular parameter loop, and prepending the same subcommand on both passes would run it twice.

Raises:

click.UsageError – on an invalid value, an unknown subcommand, or a chain-mode violation.

Return type:

list[str]