click_extra.config.formats module¶

        classDiagram
  Enum <|-- ConfigFormat
    

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