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:
EnumAll configuration formats, associated to their support status.
Each member’s value is a tuple of four elements:
The file patterns associated to the format. Patterns are fed to
wcmatch.globfor matching, and are influenced by the flags set on theConfigOptioninstance.The module backing the format, or
Nonefor a format the interpreter always supports.enabledprobes it on first use.The human-readable label of the format.
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 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_extraprobes nothing: the firstConfigOptionbuilt does.
- property mime_types: tuple[str, ...]¶
Media types a server may advertise the format as.
Feeds
format_from_mime(). Empty for a format noContent-Typeheader designates:INIandARGFILEare both served astext/plain, which names no format, andPYPROJECT_TOMLis keyed on a file name, so no media type tells it apart from plainTOML.
- click_extra.config.formats.SQLITE_CONFIG_TABLE = 'config'¶
Name of the table
click_extra.config.option.ConfigOption.load_sqlite_config()reads aSQLITEconfiguration from.The table holds
key/valuecolumns: 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
jsonreads 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:
- 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
Nonewhen 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 ofxmltodict.- Raises:
xml.parsers.expat.ExpatError – on a malformed document.
- Return type:
- 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,#textthe text of an element that also carries attributes or children, a list a run of elements sharing a tag, andNoneor 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 oneindent. A key XML does not accept as a name is respelled, like0into_0andmy keyintomy_key, so the document stays well-formed.- Return type:
- click_extra.config.formats.parse_content(fmt, content)[source]¶
Parse content with a single stateless format.
INIis excluded: it needs the CLI parameter structure for type coercion and is handled byload_ini_config().ARGFILEis excluded for the same reason: it maps command-line tokens to the CLI’s parameters and is handled byload_argfile_config().SQLITEis excluded too: it is a binary format, read from its file path byload_sqlite_config()instead of a text payload.PLISTparses here from its XML variant, the only one expressible as a text payload. The binary variant is read from its file path byload_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:
- 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
ConfigFormatexceptINI,SQLITE,ARGFILEandPYPROJECT_TOML, which have no serializer.JSON,JSON5andJSONCare emitted as plain JSON andPLISTthroughplistlib, 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
matchstatement inserialize_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 throughkwargs(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,XMLandPLISThave no null type (plistlibeven raises onNonevalues), andXMLexpects a single root mapping, so the caller is responsible for shapingdataaccordingly.INI,SQLITE,ARGFILEandPYPROJECT_TOMLhave no serializer.Note
Optional third-party serializers are imported lazily, at the point of use. Writing
TOMLuses tomlrt (the[toml]extra), unlike reading which relies on the built-intomllib.- Raises:
ValueError – the format has no serializer.
- Return type:
- 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, soapp.tomlresolves toTOMLandapp.ymltoYAML.formatsrestricts and orders the candidates (the first match wins); it defaults to everyConfigFormat.- Return type:
- 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: theContent-Typeheader is then the only thing typing the payload. The media type is matched against each format’smime_types, soapplication/tomlresolves toTOMLandtext/yamltoYAML.formatsrestricts and orders the candidates (the first match wins); it defaults to everyConfigFormat.Parameters are stripped, so a raw
application/yaml; charset=utf-8header 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+jsona private API answers with resolves toJSON. An exact match wins over a suffix.Returns
Nonefor a media type no format claims, which covers the generictext/plainandapplication/octet-streama server falls back to for an extension it does not recognize.- Return type:
- 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.enabledfinds the parser missing, and for theImportErrortext raised when such a format is requested, shared byread_file()andclick_extra.test_suite.parse_test_suite(). A format’slabel, lower-cased, is itsclick-extra[<extra>]install target, worded like every other missing optional dependency of the package.SQLITEis the exception: it reads through the standard library, so no extra installs it and it gets_NO_SQLITE_MESSAGEinstead.- Return type:
- 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()overformats(everyConfigFormatby default), then the content is parsed withparse_content().- Raises:
ValueError – the file name matches none of the candidate
formats.ImportError – the matched format’s parser is not available.
- Return type: