click_extra.config.schema module

        classDiagram
  ValueError <|-- ValidationError
  tuple <|-- SchemaFieldInfo
    

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.