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_subcommandswhich only fires when no subcommands are given on the CLI,_prepend_subcommandsalways prepends the listed subcommands. This is useful for always injecting adebugsubcommand on a dev machine, for example.Only works with
chain=Truegroups (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 asdict[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 adict(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 toEXTENSION_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 setmetadata={NORMALIZE_KEYS_METADATA_KEY: False}to keep a sub-tree’s keys verbatim, so external identifiers (likepython-versionaxis names) are not rewritten to Python-style names (python_version). Read by_from_dataclassalongsideCONFIG_PATH_METADATA_KEY.
- exception click_extra.config.schema.ValidationError(path, message, code=None)[source]¶
Bases:
ValueErrorRaised when a configuration file fails validation.
A single, structured exception type that uniformly carries the dotted
pathof the offending key, a human-readablemessage, and an optionalcodefor programmatic handling. Used by click-extra’s built-in strict-mode check and by every user-registeredConfigValidator, so downstream apps and--validate-configsee 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:
objectRegister an app-defined extension validator for one sub-tree of the configuration file.
Apps register validators via the
config_validators=kwarg onConfigOption(or the matching decorator) to extend click-extra’s built-in CLI-parameter strict check with custom validation logic. Each validator targets a single dottedextension_pathrelative 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-configand 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 namedmy-cliwithextension_path="managers"receives the contents of the[my-cli.managers]table.validator (
Callable[[dict[str,Any]],None]) – Callable taking the sub-tree dict and raisingValidationErroron 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.
- 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-barbecomesfoo_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 reads1: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 withflatten_config_keys’sopaque_keysto 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:
Note
Click applies the same substitution in
Option._parse_declsandArgument._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:
sep (
str) – Separator used to join parent and child keys. Defaults to"_"which produces valid Python identifiers when combined withnormalize_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 asdict[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:
- 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_CONFIGbyConfigOptionwhen aconfig_schemais set, orNoneif no schema was configured or no configuration was loaded.
- class click_extra.config.schema.SchemaFieldInfo(key, type_hint, default, summary, description)[source]¶
Bases:
NamedTupleDocumentation record for one option of a configuration schema.
Produced by
schema_field_infos(). Consumed by theclick:configSphinx directive, and by CLIs building their own configuration reference (ashow-configtable, 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 throughclick_extra.config.schema.CONFIG_PATH_METADATA_KEY. Nested dataclass fields contribute one segment per nesting level (test-suite.timeout).
- 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()).
- 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 withinspect.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 aclick:sourceSphinx directive). Import the schema from a real module to get its docstrings documented.
- 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), honoringclick_extra.config.schema.CONFIG_PATH_METADATA_KEYat 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.syncsorts beforeworkflow-pins.sync).Defaults are read off a pristine
schema()instance, so every field must carry a default: configuration schemas are default-complete by construction, sincemake_schema_callable()instantiates them from partial user data.- Raises:
TypeError – when
schemais not a dataclass type.- Return type:
- 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:Type-aware flattening. Fields typed as
dict[str, X]are treated as opaque:flatten_config_keysstops at their boundary so the dict value is kept intact.Field metadata. Dataclass fields may carry
click_extra.config_path(a dotted TOML path like"test-matrix.replace") andclick_extra.normalize_keys(Falseto skip key normalization on the extracted value). Fields with an explicit path are extracted from the raw config before normalization and flattening.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.
NonereturnsNone.
- Parameters:
strict (
bool) – IfTrue, raiseValueErrorwhen the config contains keys that do not match any dataclass field (after normalization and flattening).warn_unknown (
bool) – IfTrue(andstrictisFalse), 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) – IfFalse, skipnormalize_config_keyson the remaining config dict. Used internally when recursing into nested dataclasses whose parent opted out of normalization viaclick_extra.normalize_keys = False.
- Return type:
- class click_extra.config.schema.ValidationReport(schema_instance, opaque_subtrees, errors, merged_conf=None)[source]¶
Bases:
objectOutcome 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.
Nonewhen no schema is configured, or when the schema stage raised (in which case the failure is recorded inerrors).
- 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
ValidationErrordetected, in stage order (CLI-flag keys first, then schema errors, then validator failures). Empty on success.With
collect_all=Falsethis 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 payloadload_conf()layers into the context’sdefault_map, asmerge_default_map()does.Nonewhenparams_templatewasNone(no strict check) or the strict check failed.
- 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
ConfigValidatorhooks) behind a single function yielding a single error type. It is not namedvalidate_config: that name belongs tovalidate_config(), the callback powering the--validate-configflag.Stages, in order:
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’sopaque_subtrees.Strict-check the CLI-flag-bound part against
params_template, once its dotted keys are expanded, keeping the merged result as the report’smerged_conf(skipped whenparams_templateisNone). A key the dataclass schema reads is left to stage 3.Schema-build the app section through the configured callable, producing the report’s
schema_instance.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. PassNoneto 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, orNone.config_validators (
Sequence[ConfigValidator]) – Extension validators to run against opaque sub-trees.fallback_sections (
Sequence[str]) – Legacy section names to try whenapp_nameis 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 (seewarn_unknowninmake_schema_callable()). Ignored whenschema_strictrejects 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) – WhenTrue(default), run every stage and collect all errors. WhenFalse, the first error short-circuits the rest.
- Return type:
- Returns:
A
ValidationReport.ValidationErroris the single error type recorded by every stage; aValueErrororTypeErrorraised by the schema callable is wrapped into it.