### Install ConfigUpdater Source: https://configupdater.readthedocs.io/en/latest/usage.html Install the package via pip. ```bash pip install configupdater ``` -------------------------------- ### Initialize and Read Configuration Source: https://configupdater.readthedocs.io/en/latest/usage.html Basic setup to load a configuration file into the updater. ```python from configupdater import ConfigUpdater updater = ConfigUpdater() updater.read("setup.cfg") ``` -------------------------------- ### Install Pre-commit Hooks Source: https://configupdater.readthedocs.io/en/latest/contributing.html Install the pre-commit framework and its associated hooks to automatically check your code style and quality before committing. ```bash pip install pre-commit pre-commit install ``` -------------------------------- ### Define Configuration String Source: https://configupdater.readthedocs.io/en/latest/usage.html Example configuration string used for demonstration purposes. ```python cfg = """ [metadata] author = Ada Lovelace summary = The Analytical Engine """ ``` -------------------------------- ### Add and Remove Options Source: https://configupdater.readthedocs.io/en/latest/_sources/usage.rst.txt Examples for adding options, adding comments, and renaming keys within a configuration section. ```python cfg = """ [metadata] author = Ada Lovelace summary = The Analytical Engine """ ``` ```python updater = ConfigUpdater() updater.read_string(cfg) updater["metadata"]["license"] = "MIT" ``` ```python updater = ConfigUpdater() updater.read_string(cfg) (updater["metadata"]["summary"].add_before .comment("Ada would have loved MIT") .option("license", "MIT")) ``` ```python updater = ConfigUpdater() updater.read_string(cfg) (updater["metadata"]["author"].add_after .comment("Ada would have loved MIT") .option("license", "MIT")) ``` ```python updater = ConfigUpdater() updater.read_string(cfg) updater["metadata"]["summary"].key = "description" ``` -------------------------------- ### Configuration Retrieval Methods Source: https://configupdater.readthedocs.io/en/latest/api.html Methods for getting configuration options and sections. ```APIDOC ## GET /configupdater ### Description Retrieves configuration values. The `get` method allows fetching an option with an optional fallback value. If the option does not exist and no fallback is provided, it raises a `NoOptionError`. The `get_section` method retrieves an entire section or a default value if the section is not found. ### Method GET ### Endpoint /configupdater ### Parameters #### Query Parameters - **section** (str) - Required - The name of the section to retrieve the option from. - **option** (str) - Required - The name of the option to retrieve. - **fallback** (Option) - Optional - A default `Option` object to return if the specified option is not found. ### Response #### Success Response (200) - **Option** (object) - An Option object containing the key/value pair if found, or the fallback value. #### Error Response - **NoSectionError** - Raised if the specified section cannot be found. - **NoOptionError** - Raised if the option cannot be found and no fallback was given. ### Request Example ```json { "section": "database", "option": "port", "fallback": {"name": "default_port", "value": 5432} } ``` ### Response Example ```json { "name": "port", "value": 5432 } ``` ``` -------------------------------- ### Get Item from Configuration Source: https://configupdater.readthedocs.io/en/latest/_modules/configparser.html Retrieves an item by key. Raises KeyError if the key is not the default section and does not exist. ```python def __getitem__(self, key): if key != self.default_section and not self.has_section(key): raise KeyError(key) return self._proxies[key] ``` -------------------------------- ### Get Length of Configuration Source: https://configupdater.readthedocs.io/en/latest/_modules/configparser.html Returns the number of sections in the configuration, including the default section. ```python def __len__(self): return len(self._sections) + 1 # the default section ``` -------------------------------- ### Activate Conda Environment Source: https://configupdater.readthedocs.io/en/latest/contributing.html Activate the 'configupdater' Conda environment before starting development to ensure you are using the correct dependencies. ```bash source activate configupdater ``` -------------------------------- ### SectionProxy Get Name Source: https://configupdater.readthedocs.io/en/latest/_modules/configparser.html Provides read-only access to the name of the section. ```python @property def name(self): # The name of the section on a proxy is read-only. return self._name ``` -------------------------------- ### Read and Modify Configuration Source: https://configupdater.readthedocs.io/en/latest/_sources/usage.rst.txt Basic initialization, reading a file, updating a value, and printing the result. ```python from configupdater import ConfigUpdater updater = ConfigUpdater() updater.read("setup.cfg") ``` ```python updater["metadata"]["author"].value = "Alan Turing" ``` ```python print(updater) ``` -------------------------------- ### SectionProxy Get Option Source: https://configupdater.readthedocs.io/en/latest/_modules/configparser.html Retrieves an option value from the section, with an optional fallback value. ```python def get(self, option, fallback=None, *, raw=False, vars=None, _impl=None, **kwargs): """Get an option value. Unless `fallback` is provided, `None` will be returned if the option is not found. """ # If `_impl` is provided, it should be a getter method on the parser # object that provides the desired type conversion. if not _impl: _impl = self._parser.get ``` -------------------------------- ### Initialize ConfigParser with custom delimiters Source: https://configupdater.readthedocs.io/en/latest/_modules/configparser.html Demonstrates initializing a ConfigParser instance with custom delimiters for key-value pairs. This is useful when the default '=' or ':' characters are present in configuration values. ```python OPTCRE_NV = re.compile(_OPT_NV_TMPL.format(delim="=|"), re.VERBOSE) NONSPACECRE = re.compile(r"\S") BOOLEAN_STATES = {'1': True, 'yes': True, 'true': True, 'on': True, '0': False, 'no': False, 'false': False, 'off': False} def __init__(self, defaults=None, dict_type=_default_dict, allow_no_value=False, *, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section=DEFAULTSECT, interpolation=_UNSET, converters=_UNSET): self._dict = dict_type self._sections = self._dict() self._defaults = self._dict() self._converters = ConverterMapping(self) self._proxies = self._dict() self._proxies[default_section] = SectionProxy(self, default_section) self._delimiters = tuple(delimiters) if delimiters == ('=', ':'): self._optcre = self.OPTCRE_NV if allow_no_value else self.OPTCRE else: d = "|".join(re.escape(d) for d in delimiters) if allow_no_value: self._optcre = re.compile(self._OPT_NV_TMPL.format(delim=d), re.VERBOSE) else: self._optcre = re.compile(self._OPT_TMPL.format(delim=d), re.VERBOSE) self._comment_prefixes = tuple(comment_prefixes or ()) self._inline_comment_prefixes = tuple(inline_comment_prefixes or ()) self._strict = strict self._allow_no_value = allow_no_value self._empty_lines_in_values = empty_lines_in_values self.default_section=default_section self._interpolation = interpolation if self._interpolation is _UNSET: self._interpolation = self._DEFAULT_INTERPOLATION if self._interpolation is None: self._interpolation = Interpolation() if not isinstance(self._interpolation, Interpolation): raise TypeError( f"interpolation= must be None or an instance of Interpolation;" f" got an object of type {type(self._interpolation)}" ) if converters is not _UNSET: self._converters.update(converters) if defaults: self._read_defaults(defaults) ``` -------------------------------- ### SectionProxy Get Item Source: https://configupdater.readthedocs.io/en/latest/_modules/configparser.html Retrieves an option from the section, raising KeyError if the option does not exist. ```python def __getitem__(self, key): if not self._parser.has_option(self._name, key): raise KeyError(key) return self._parser.get(self._name, key) ``` -------------------------------- ### Option Initialization Source: https://configupdater.readthedocs.io/en/latest/_modules/configupdater/option.html Details on how to initialize an Option object. ```APIDOC ## Option Initialization ### Description Initializes an Option object with a key and an optional value. It can also be associated with a container (like a Section) and specific formatting options. ### Parameters - **key** (str) - Required - The name of the configuration option. - **value** (Optional[str]) - Optional - The initial value for the option. If None, it's treated as an option without a value. - **container** (Optional['Section']) - Optional - The parent Section object this option belongs to. - **delimiter** (str) - Optional - The delimiter character to use (defaults to '='). - **space_around_delimiters** (bool) - Optional - Whether to include spaces around the delimiter (defaults to True). - **line** (Optional[str]) - Optional - A raw line string from the configuration file to initialize the option. ``` -------------------------------- ### Display Configuration Output Source: https://configupdater.readthedocs.io/en/latest/usage.html The resulting configuration structure after adding an option. ```ini [metadata] author = Ada Lovelace summary = The Analytical Engine license = MIT ``` -------------------------------- ### Utility Methods Source: https://configupdater.readthedocs.io/en/latest/api.html Helper methods for configuration management. ```APIDOC ## GET /configupdater/utils ### Description Provides utility methods for configuration management, such as listing section names, option names, and transforming option keys. ### Method GET ### Endpoint /configupdater/utils ### Parameters #### Query Parameters - **action** (str) - Required - The utility action to perform ('sections', 'options', 'optionxform'). - **section** (str) - Optional - The name of the section (required if action is 'options'). - **optionstr** (str) - Optional - The option string to transform (required if action is 'optionxform'). ### Response #### Success Response (200) - **result** (list | str) - The result of the utility action (e.g., a list of section names, option names, or a transformed option string). ### Request Example (list sections) ```json { "action": "sections" } ``` ### Response Example (list sections) ```json { "result": ["section1", "section2"] } ``` ### Request Example (transform option) ```json { "action": "optionxform", "optionstr": "MyOption" } ``` ### Response Example (transform option) ```json { "result": "myoption" } ``` ``` -------------------------------- ### SectionProxy Get Parser Source: https://configupdater.readthedocs.io/en/latest/_modules/configparser.html Provides read-only access to the parser object associated with the section proxy. ```python @property def parser(self): # The parser object of the proxy is read-only. return self._parser ``` -------------------------------- ### Resulting Configuration with Comments Source: https://configupdater.readthedocs.io/en/latest/usage.html The output format after inserting an option with a comment. ```ini [metadata] author = Ada Lovelace # Ada would have loved MIT license = MIT summary = Analytical Engine calculating the Bernoulli numbers ``` -------------------------------- ### Calculate value start index Source: https://configupdater.readthedocs.io/en/latest/_modules/configupdater/option.html Returns the column index where the value begins, useful for indentation calculations. ```python def value_start_idx(self) -> int: """Index where the value of the option starts, good for indentation""" delim = self._get_delim(determine_suffix=False) return len(f"{self._key}{delim}") ``` -------------------------------- ### write Source: https://configupdater.readthedocs.io/en/latest/_modules/configupdater/configupdater.html Writes the current configuration state to a file-like object. ```APIDOC ## write ### Description Write an .cfg/.ini-format representation of the configuration state. ### Parameters - **fp** (file-like object) - Required - Open file handle - **validate** (Boolean) - Optional - Validate format before writing ``` -------------------------------- ### Resulting configuration structure Source: https://configupdater.readthedocs.io/en/latest/usage.html The expected output format after injecting the build_sphinx section. ```ini [metadata] author = Ada Lovelace summary = The Analytical Engine [build_sphinx] source_dir = docs build_dir = docs/_build ``` -------------------------------- ### Option Iteration and Items Source: https://configupdater.readthedocs.io/en/latest/_modules/configupdater/section.html Methods for iterating over configuration options and retrieving them as a list of tuples. ```APIDOC ## GET /api/options ### Description Returns a list of (name, option) tuples for each option in this section. This method preserves the order of options. ### Method GET ### Endpoint `/api/options` ### Response #### Success Response (200) - **List[Tuple[str, Option]]** (list) - A list where each element is a tuple containing the option's key (string) and the Option object. #### Response Example ```json [ ["option1", {"key": "option1", "value": "value1"}], ["option2", {"key": "option2", "value": "value2"}] ] ``` ``` -------------------------------- ### Get Boolean Option Source: https://configupdater.readthedocs.io/en/latest/_modules/configparser.html Retrieves an option value and converts it to a boolean. Supports interpolation, raw retrieval, and fallback values. ```python def getboolean(self, section, option, *, raw=False, vars=None, fallback=_UNSET, **kwargs): return self._get_conv(section, option, self._convert_to_boolean, ``` -------------------------------- ### POST /read Source: https://configupdater.readthedocs.io/en/latest/_modules/configupdater/parser.html Reads and parses a configuration file from the specified path into a Document object. ```APIDOC ## POST /read ### Description Reads and parses a configuration file from the specified path into a Document object. ### Method POST ### Endpoint /read ### Parameters #### Request Body - **filename** (str) - Required - Path to the configuration file. - **encoding** (str) - Optional - Encoding of the file, defaults to None. - **into** (Document) - Optional - An existing Document object to be populated with the parsed configuration. ### Response #### Success Response (200) - **document** (Document) - The populated Document object containing the parsed configuration data. ``` -------------------------------- ### Initialize Option class Source: https://configupdater.readthedocs.io/en/latest/api.html Constructor for creating an Option block representing a key/value pair. ```python class configupdater.Option(_key : str_, _value : str | None = None_, _container : Section | None = None_, _delimiter : str = '='_, _space_around_delimiters : bool = True_, _line : str | None = None_)[source] ``` -------------------------------- ### Get Float Option Source: https://configupdater.readthedocs.io/en/latest/_modules/configparser.html Retrieves an option value and converts it to a float. Supports interpolation, raw retrieval, and fallback values. ```python def getfloat(self, section, option, *, raw=False, vars=None, fallback=_UNSET, **kwargs): return self._get_conv(section, option, float, raw=raw, vars=vars, fallback=fallback, **kwargs) ``` -------------------------------- ### Read Configuration Files Source: https://configupdater.readthedocs.io/en/latest/_modules/configupdater/configupdater.html Methods for loading configuration data from a file path or a file-like object. ```python def read(self: T, filename: PathLike, encoding: Optional[str] = None) -> T: """Read and parse a filename. Args: filename (str): path to file encoding (str): encoding of file, default None """ self.clear() self._filename = filename return self._parser().read(filename, encoding, self) def read_file(self: T, f: Iterable[str], source: Optional[str] = None) -> T: """Like read() but the argument must be a file-like object. ``` -------------------------------- ### Get Integer Option Source: https://configupdater.readthedocs.io/en/latest/_modules/configparser.html Retrieves an option value and converts it to an integer. Supports interpolation, raw retrieval, and fallback values. ```python def getint(self, section, option, *, raw=False, vars=None, fallback=_UNSET, **kwargs): return self._get_conv(section, option, int, raw=raw, vars=vars, fallback=fallback, **kwargs) ``` -------------------------------- ### Write configuration to file Source: https://configupdater.readthedocs.io/en/latest/_modules/configparser.html Writes the current configuration state to an .ini-format file. Comments are not preserved. ```python def write(self, fp, space_around_delimiters=True): """Write an .ini-format representation of the configuration state. If `space_around_delimiters` is True (the default), delimiters between keys and values are surrounded by spaces. Please note that comments in the original configuration file are not preserved when writing the configuration back. """ if space_around_delimiters: d = " {} ".format(self._delimiters[0]) else: d = self._delimiters[0] if self._defaults: self._write_section(fp, self.default_section, self._defaults.items(), d) for section in self._sections: self._write_section(fp, section, self._sections[section].items(), d) ``` -------------------------------- ### Get section names from ConfigParser Source: https://configupdater.readthedocs.io/en/latest/_modules/configparser.html Returns a list of all section names present in the configuration, excluding the special [DEFAULT] section. ```python def sections(self): """Return a list of section names, excluding [DEFAULT]""" # self._sections will never have [DEFAULT] in it return list(self._sections.keys()) ``` -------------------------------- ### Get default values from ConfigParser Source: https://configupdater.readthedocs.io/en/latest/_modules/configparser.html Retrieves the default values set for the configuration. These defaults are applied when a specific option is not found in any section. ```python def defaults(self): return self._defaults ``` -------------------------------- ### Read Configuration from String Source: https://configupdater.readthedocs.io/en/latest/_modules/configparser.html Reads configuration directly from a string. This method uses io.StringIO to treat the string as a file. ```python def read_string(self, string, source='') """Read configuration from a given string.""" sfile = io.StringIO(string) self.read_file(sfile, source) ``` -------------------------------- ### Retrieve option names Source: https://configupdater.readthedocs.io/en/latest/_modules/configupdater/section.html Returns a list of all option keys as strings. ```python def options(self) -> List[str]: """Returns option names Returns: list: list of option names as strings """ return [option.key for option in self.iter_options()] ``` -------------------------------- ### Regex for Matching Leading Whitespace Source: https://configupdater.readthedocs.io/en/latest/_modules/configupdater/parser.html A simple regular expression to find the first non-whitespace character on a line, useful for identifying the start of content. ```python NONSPACECRE = re.compile(r"\S") ``` -------------------------------- ### Get all option names for a section Source: https://configupdater.readthedocs.io/en/latest/_modules/configparser.html Retrieves a list of all option names within a specified section, including any inherited from the defaults. Raises NoSectionError if the section does not exist. ```python def options(self, section): """Return a list of option names for the given section name.""" try: opts = self._sections[section].copy() except KeyError: raise NoSectionError(section) from None opts.update(self._defaults) return list(opts.keys()) ``` -------------------------------- ### Initialize Parser class Source: https://configupdater.readthedocs.io/en/latest/api.html Constructor for the Parser class used to update configuration files. ```python class configupdater.Parser(_allow_no_value=False, *, delimiters: ~typing.Tuple[str, ...] = ('=', ':'), comment_prefixes: ~typing.Tuple[str, ...] = ('#', ';'), inline_comment_prefixes: ~typing.Tuple[str, ...] | None = None, strict: bool = True, empty_lines_in_values: bool = True, space_around_delimiters: bool = True, optionxform: ~typing.Callable[[str], str] = _)[source] ``` -------------------------------- ### Get Option Value as List Source: https://configupdater.readthedocs.io/en/latest/_modules/configupdater/option.html Retrieves the option's value, splitting multi-line values into a list. Handles cases where the value is None by returning an empty list. ```python def as_list(self, separator="\n") -> List[str]: """Returns the (multi-line/element) value as a list Empty list if value is None, single-element list for a one-element value and an element for each line in a multi-element value. Args: separator (str): separator for values, default: line separator """ if self._value_is_none: return [] else: return [v.strip() for v in cast(str, self.value).strip().split(separator)] ``` -------------------------------- ### Run Unit Tests Source: https://configupdater.readthedocs.io/en/latest/contributing.html Execute the project's unit tests to ensure your changes have not introduced any regressions. Add new tests if you are introducing new features. ```bash python setup.py test ``` -------------------------------- ### Internal Helper for Getting and Converting Values Source: https://configupdater.readthedocs.io/en/latest/_modules/configparser.html Internal helper method to retrieve an option and convert it using a specified function. Catches `NoSectionError` and `NoOptionError` and returns a fallback value if provided. ```python def _get_conv(self, section, option, conv, *, raw=False, vars=None, fallback=_UNSET, **kwargs): try: return self._get(section, conv, option, raw=raw, vars=vars, **kwargs) except (NoSectionError, NoOptionError): if fallback is _UNSET: raise return fallback ``` -------------------------------- ### Get Option Value with Fallback Source: https://configupdater.readthedocs.io/en/latest/_modules/configparser.html Retrieves an option's value from a section. Supports variable interpolation, raw retrieval, and fallback values if the option or section is not found. Arguments `raw`, `vars`, and `fallback` are keyword-only. ```python def get(self, section, option, *, raw=False, vars=None, fallback=_UNSET): """Get an option value for a given section. If `vars` is provided, it must be a dictionary. The option is looked up in `vars` (if provided), `section`, and in `DEFAULTSECT` in that order. If the key is not found and `fallback` is provided, it is used as a fallback value. `None` can be provided as a `fallback` value. If interpolation is enabled and the optional argument `raw` is False, all interpolations are expanded in the return values. Arguments `raw`, `vars`, and `fallback` are keyword only. The section DEFAULT is special. """ try: d = self._unify_values(section, vars) except NoSectionError: if fallback is _UNSET: raise else: return fallback option = self.optionxform(option) try: value = d[option] except KeyError: if fallback is _UNSET: raise NoOptionError(option, section) else: return fallback if raw or value is None: return value else: return self._interpolation.before_get(self, section, option, value, d) ``` -------------------------------- ### Define a section as a multi-line string Source: https://configupdater.readthedocs.io/en/latest/usage.html Define a new configuration section using a multi-line string for declarative injection. ```python sphinx_sect_str = """ [build_sphinx] source_dir = docs build_dir = docs/_build """ ``` -------------------------------- ### Configuration Reading and Iteration Source: https://configupdater.readthedocs.io/en/latest/api.html Methods for reading configuration from files or strings, and iterating over sections and options. ```APIDOC ## POST /configupdater/read ### Description Reads and parses configuration from a specified source, which can be a filename, a file-like object, or a string. ### Method POST ### Endpoint /configupdater/read ### Parameters #### Request Body - **source_type** (str) - Required - Type of source ('filename', 'file_object', 'string'). - **source_data** (str | object) - Required - The actual data for the source (e.g., file path, string content). - **encoding** (str) - Optional - The encoding of the file if reading from a filename or file object. ### Response #### Success Response (200) - **status** (str) - Indicates success, e.g., "Configuration read successfully." ### Request Example (from string) ```json { "source_type": "string", "source_data": "[section]\noption = value" } ``` ### Response Example ```json { "status": "Configuration read successfully." } ``` ## GET /configupdater/iterate ### Description Provides iterators for sections, options, or blocks within the configuration. ### Method GET ### Endpoint /configupdater/iterate ### Parameters #### Query Parameters - **type** (str) - Required - Type of iteration ('sections', 'options', 'blocks'). - **section_name** (str) - Optional - The name of the section to iterate options from. Required if type is 'options'. ### Response #### Success Response (200) - **items** (list) - A list of items based on the iteration type (e.g., section names, option names, or block objects). ### Request Example (iterate sections) ```json { "type": "sections" } ``` ### Response Example (iterate sections) ```json { "items": ["section1", "section2"] } ``` ``` -------------------------------- ### Read configuration file Source: https://configupdater.readthedocs.io/en/latest/api.html Methods for reading and parsing configuration files from a path. ```python read(_filename : str | bytes | PathLike_, _encoding : str | None = None_) → Document[source] ``` ```python read(_filename : str | bytes | PathLike_, _encoding : str_, _into : D_) → D ``` ```python read(_filename : str | bytes | PathLike_, _*_ , _into : D_, _encoding : str | None = None_) → D ``` -------------------------------- ### Read Configuration from File Source: https://configupdater.readthedocs.io/en/latest/_modules/configupdater/parser.html Parses configuration from an iterable file-like object. The 'f' argument must be iterable and return one line at a time. ```python def read_file(self, f: Iterable[str], source: Optional[str]) -> Document: ... @overload def read_file(self, f: Iterable[str], source: Optional[str], into: D) -> D: ... @overload def read_file( self, f: Iterable[str], *, into: D, source: Optional[str] = None ) -> D: ... [docs] def read_file(self, f, source=None, into=None): """Like read() but the argument must be a file-like object. The ``f`` argument must be iterable, returning one line at a time. Optional second argument is the ``source`` specifying the name of the file being read. If not given, it is taken from f.name. If ``f`` has no ``name`` attribute, ```` is used. Args: f: file like object source (Optional[str]): reference name for file object, default None into (Optional[Document]): object to be populated with the parsed config """ if isinstance(f, str): raise RuntimeError("f must be a file-like object, not string!") document = Document() if into is None else into if source is None: try: source = cast(str, cast(io.FileIO, f).name) except AttributeError: source = "" self._read(f, source, document) return document ``` -------------------------------- ### Write configuration to a file Source: https://configupdater.readthedocs.io/en/latest/_modules/configupdater/configupdater.html Writes the current configuration state to a file-like object. Validation can be performed before writing. ```python def write(self, fp: TextIO, validate: bool = True): # TODO: For Python>=3.8 instead of TextIO we can define a Writeable protocol """Write an .cfg/.ini-format representation of the configuration state. Args: fp (file-like object): open file handle validate (Boolean): validate format before writing """ if validate: self.validate_format() fp.write(str(self)) ``` -------------------------------- ### ConfigParser Read Method Source: https://configupdater.readthedocs.io/en/latest/_modules/configupdater/parser.html Reads and parses a configuration file from the specified path. It can optionally populate an existing Document object. ```python @overload def read(self, filename: PathLike, encoding: Optional[str] = None) -> Document: ... @overload def read(self, filename: PathLike, encoding: str, into: D) -> D: ... @overload def read( self, filename: PathLike, *, into: D, encoding: Optional[str] = None ) -> D: ... def read(self, filename, encoding=None, into=None): """Read and parse a filename. Args: filename (str): path to file encoding (Optional[str]): encoding of file, default None into (Optional[Document]): object to be populated with the parsed config """ document = Document() if into is None else into with open(filename, encoding=encoding) as fp: self._read(fp, str(filename), document) self._filename = os.path.abspath(filename) return document ``` -------------------------------- ### Add Options to Configuration Source: https://configupdater.readthedocs.io/en/latest/usage.html Append a new key/value pair to a section. ```python updater = ConfigUpdater() updater.read_string(cfg) updater["metadata"]["license"] = "MIT" ``` -------------------------------- ### Read configuration from a string Source: https://configupdater.readthedocs.io/en/latest/_modules/configupdater/configupdater.html Parses a configuration string into the object. The source parameter defaults to ''. ```python def read_string(self: T, string: str, source="") -> T: """Read configuration from a given string. Args: string (str): string containing a configuration source (str): reference name for file object, default '' """ self.clear() return self._parser().read_string(string, source, self) ``` -------------------------------- ### Read configuration from file-like object Source: https://configupdater.readthedocs.io/en/latest/api.html Methods for reading and parsing configuration from an iterable file-like object. ```python read_file(_f : Iterable[str]_, _source : str | None_) → Document[source] ``` ```python read_file(_f : Iterable[str]_, _source : str | None_, _into : D_) → D ``` ```python read_file(_f : Iterable[str]_, _*_ , _into : D_, _source : str | None = None_) → D ``` -------------------------------- ### Section Methods Source: https://configupdater.readthedocs.io/en/latest/_modules/configupdater/section.html Methods for adding options, comments, and spaces to a configuration section. ```APIDOC ## add_option ### Description Adds an Option object to the section. Primarily used during initial parsing. ### Parameters #### Request Body - **entry** (Option) - Required - Key value pair as Option object ## add_comment ### Description Adds a Comment object to the section. If the last block is already a comment, it appends the line to it. ### Parameters #### Request Body - **line** (str) - Required - One line in the comment ## add_space ### Description Adds a Space object to the section. If the last block is already a space, it appends the line to it. ### Parameters #### Request Body - **line** (str) - Required - One line that defines the space ``` -------------------------------- ### Read Configuration from String Source: https://configupdater.readthedocs.io/en/latest/_modules/configupdater/parser.html Parses configuration data provided as a string. Internally converts the string to a file-like object before processing. ```python @overload def read_string(self, string: str, source: str = "") -> Document: ... @overload def read_string(self, string: str, source: str, into: D) -> D: ... @overload def read_string(self, string: str, *, into: D, source: str = "") -> D: ... [docs] def read_string(self, string, source="", into=None): """Read configuration from a given string. Args: string (str): string containing a configuration source (str): reference name for file object, default '' into (Optional[Document]): object to be populated with the parsed config """ sfile = io.StringIO(string) return self.read_file(sfile, source, into) ``` -------------------------------- ### Read configuration from files Source: https://configupdater.readthedocs.io/en/latest/_modules/configparser.html Reads and parses configuration from one or more files. Files that cannot be opened are ignored. Returns a list of successfully read filenames. ```python def read(self, filenames, encoding=None): """Read and parse a filename or an iterable of filenames. Files that cannot be opened are silently ignored; this is designed so that you can specify an iterable of potential configuration file locations (e.g. current directory, user's home directory, systemwide directory), and all existing configuration files in the iterable will be read. A single filename may also be given. Return list of successfully read files. """ if isinstance(filenames, (str, bytes, os.PathLike)): filenames = [filenames] encoding = io.text_encoding(encoding) read_ok = [] for filename in filenames: try: with open(filename, encoding=encoding) as fp: self._read(fp, filename) except OSError: continue if isinstance(filename, os.PathLike): filename = os.fspath(filename) read_ok.append(filename) return read_ok ``` -------------------------------- ### Add Sections with Formatting Source: https://configupdater.readthedocs.io/en/latest/usage.html Insert a new section before an existing one with comments and spacing. ```python updater = ConfigUpdater() updater.read_string(cfg) (updater["metadata"].add_before .comment("Some specific project options") .section("options") .space(2)) ``` -------------------------------- ### Clone ConfigUpdater Repository Source: https://configupdater.readthedocs.io/en/latest/contributing.html Clone the ConfigUpdater repository from GitHub to your local machine after forking it. Replace 'YourLogin' with your GitHub username. ```bash git clone git@github.com:YourLogin/configupdater.git ``` -------------------------------- ### Retrieve Options Source: https://configupdater.readthedocs.io/en/latest/_modules/configupdater/section.html Methods to list or export options from a section. ```APIDOC ## options() ### Description Returns a list of all option names within the section. ### Response - **list** (List[str]) - A list of option keys. ## to_dict() ### Description Transforms the section options into a standard dictionary. ### Response - **dict** (Dict[str, Optional[str]]) - A dictionary mapping option keys to their values. ``` -------------------------------- ### Read Configuration from Dictionary Source: https://configupdater.readthedocs.io/en/latest/_modules/configparser.html Reads configuration from a dictionary. Keys are section names, and values are dictionaries of options. All types are converted to strings. Handles duplicate sections and options based on the strict mode. ```python def read_dict(self, dictionary, source='') """Read configuration from a dictionary. Keys are section names, values are dictionaries with keys and values that should be present in the section. If the used dictionary type preserves order, sections and their keys will be added in order. All types held in the dictionary are converted to strings during reading, including section names, option names and keys. Optional second argument is the `source` specifying the name of the dictionary being read. """ elements_added = set() for section, keys in dictionary.items(): section = str(section) try: self.add_section(section) except (DuplicateSectionError, ValueError): if self._strict and section in elements_added: raise elements_added.add(section) for key, value in keys.items(): key = self.optionxform(str(key)) if value is not None: value = str(value) if self._strict and (section, key) in elements_added: raise DuplicateOptionError(section, key, source) elements_added.add((section, key)) self.set(section, key, value) ``` -------------------------------- ### ConfigUpdater Class Initialization Source: https://configupdater.readthedocs.io/en/latest/_modules/configupdater/configupdater.html Initializes a ConfigUpdater object with various syntax options. These options control how the configuration files are parsed and interpreted. ```APIDOC ## ConfigUpdater ### Description Tool to parse and modify existing ``cfg`` files. ConfigUpdater follows the API of ConfigParser with some differences: * inline comments are treated as part of a key's value, * only a single config file can be updated at a time, * the original case of sections and keys are kept, * control over the position of a new section/key. Following features are **deliberately not** implemented: * interpolation of values, * propagation of parameters from the default section, * conversions of values, * passing key/value-pairs with ``default`` argument, * non-strict mode allowing duplicate sections and keys. **ConfigUpdater** objects can be created by passing the same kind of arguments accepted by the :class:`Parser`. After a ConfigUpdater object is created, you can load some content into it by calling any of the ``read*`` methods (:meth:`read`, :meth:`read_file` and :meth:`read_string`). Once the content is loaded you can use the ConfigUpdater object more or less in the same way you would use a nested dictionary. Please have a look into :class:`Document` to understand the main differences. When you are done changing the configuration file, you can call :meth:`write` or :meth:`update_file` methods. ### Method __init__ ### Parameters #### Keyword Arguments - **allow_no_value** (bool) - Optional - Allows options without a value. - **delimiters** (Tuple[str, ...]) - Optional - Default: ('=', ':'). Characters that separate option names from values. - **comment_prefixes** (Tuple[str, ...]) - Optional - Default: ('#', ';'). Characters that start a comment. - **inline_comment_prefixes** (Optional[Tuple[str, ...]]) - Optional - Characters that start an inline comment. - **strict** (bool) - Optional - Default: True. If True, disallows duplicate sections. - **empty_lines_in_values** (bool) - Optional - Default: True. Allows empty lines within option values. - **space_around_delimiters** (bool) - Optional - Default: True. Allows spaces around delimiters. ### Request Example ```python from configupdater import ConfigUpdater updater = ConfigUpdater( delimiters=("=",), comment_prefixes=("#",), inline_comment_prefixes=("//",), strict=False, empty_lines_in_values=False, space_around_delimiters=False ) ``` ``` -------------------------------- ### Read configuration from a file-like object Source: https://configupdater.readthedocs.io/en/latest/_modules/configparser.html Reads and parses configuration from a file-like object. The 'source' parameter can be used to provide a filename for error reporting. ```python def read_file(self, f, source=None): ``` -------------------------------- ### Check for Item Existence in Configuration Source: https://configupdater.readthedocs.io/en/latest/_modules/configparser.html Checks if a key exists in the configuration. Considers the default section. ```python def __contains__(self, key): return key == self.default_section or self.has_section(key) ``` -------------------------------- ### Initialize ConfigUpdater Class Source: https://configupdater.readthedocs.io/en/latest/_modules/configupdater/configupdater.html The ConfigUpdater class manages configuration file parsing and modification. It accepts various parser options to control delimiters, comment prefixes, and strictness. ```python class ConfigUpdater(Document): """Tool to parse and modify existing ``cfg`` files. ConfigUpdater follows the API of ConfigParser with some differences: * inline comments are treated as part of a key's value, * only a single config file can be updated at a time, * the original case of sections and keys are kept, * control over the position of a new section/key. Following features are **deliberately not** implemented: * interpolation of values, * propagation of parameters from the default section, * conversions of values, * passing key/value-pairs with ``default`` argument, * non-strict mode allowing duplicate sections and keys. **ConfigUpdater** objects can be created by passing the same kind of arguments accepted by the :class:`Parser`. After a ConfigUpdater object is created, you can load some content into it by calling any of the ``read*`` methods (:meth:`read`, :meth:`read_file` and :meth:`read_string`). Once the content is loaded you can use the ConfigUpdater object more or less in the same way you would use a nested dictionary. Please have a look into :class:`Document` to understand the main differences. When you are done changing the configuration file, you can call :meth:`write` or :meth:`update_file` methods. """ def __init__( self, allow_no_value=False, *, delimiters: Tuple[str, ...] = ("=", ":"), comment_prefixes: Tuple[str, ...] = ("#", ";"), inline_comment_prefixes: Optional[Tuple[str, ...]] = None, strict: bool = True, empty_lines_in_values: bool = True, space_around_delimiters: bool = True, ): self._parser_opts = { "allow_no_value": allow_no_value, "delimiters": delimiters, "comment_prefixes": comment_prefixes, "inline_comment_prefixes": inline_comment_prefixes, "strict": strict, "empty_lines_in_values": empty_lines_in_values, "space_around_delimiters": space_around_delimiters, } self._syntax_options = ReadOnlyMapping(self._parser_opts) self._filename: Optional[PathLike] = None super().__init__() ``` -------------------------------- ### NoConfigFileReadError Source: https://configupdater.readthedocs.io/en/latest/_modules/configupdater/configupdater.html Custom exception raised when an update is requested but no configuration file has been read yet. ```APIDOC ## NoConfigFileReadError ### Description Raised when no configuration file was read but update requested. ### Method (Exception class) ### Endpoint N/A ### Parameters N/A ### Request Example ```python from configupdater import ConfigUpdater, NoConfigFileReadError try: updater = ConfigUpdater() # Attempt to update without reading a file first updater.update_file('some_file.cfg') except NoConfigFileReadError as e: print(f"Error: {e}") ``` ### Response N/A (This is an exception class, not an endpoint.) ``` -------------------------------- ### Configuration Reading Methods Source: https://configupdater.readthedocs.io/en/latest/_modules/configparser.html Methods for loading configuration data into the parser from different input formats. ```APIDOC ## read_file(f, source=None) ### Description Reads configuration from a file-like object. ### Parameters #### Request Body - **f** (file-like object) - Required - Iterable object returning one line at a time. - **source** (string) - Optional - Name of the file being read. ## read_string(string, source='') ### Description Reads configuration from a given string. ### Parameters #### Request Body - **string** (string) - Required - Configuration data in string format. - **source** (string) - Optional - Name of the source. ## read_dict(dictionary, source='') ### Description Reads configuration from a dictionary where keys are section names and values are dictionaries of options. ### Parameters #### Request Body - **dictionary** (dict) - Required - Configuration data structure. - **source** (string) - Optional - Name of the source. ``` -------------------------------- ### ConfigUpdater Core Methods Source: https://configupdater.readthedocs.io/en/latest/genindex.html Methods for reading, writing, and managing configuration data within the ConfigUpdater class. ```APIDOC ## ConfigUpdater Methods ### Description Core methods for interacting with configuration files, including reading from files or strings, updating values, and writing changes back to disk. ### Methods - **read(filenames)**: Reads and parses configuration files. - **read_file(f)**: Reads a configuration file object. - **read_string(string)**: Reads configuration data from a string. - **write(fp)**: Writes the configuration to a file object. - **update_file()**: Updates the source file with current changes. - **remove_option(section, option)**: Removes an option from a section. - **remove_section(section)**: Removes an entire section. - **set(section, option, value)**: Sets an option value within a section. - **sections()**: Returns a list of available sections. ``` -------------------------------- ### ConfigUpdater.read_file Source: https://configupdater.readthedocs.io/en/latest/_modules/configupdater/configupdater.html Reads and parses configuration content from a file-like object. This method is similar to `read()` but accepts an iterable of strings representing file content. ```APIDOC ## GET /read_file ### Description Like read() but the argument must be a file-like object. ### Method read_file ### Endpoint (Implicitly called on a ConfigUpdater object) ### Parameters #### Path Parameters - **f** (Iterable[str]) - Required - A file-like object (iterable of strings). #### Query Parameters - **source** (Optional[str]) - Optional - An optional source name for the file-like object. ### Request Example ```python from configupdater import ConfigUpdater updater = ConfigUpdater() with open('config.ini', 'r') as f: updater.read_file(f, source='config.ini') ``` ### Response #### Success Response (200) - **ConfigUpdater** (ConfigUpdater) - The updated ConfigUpdater object. #### Response Example (The response is the modified ConfigUpdater object itself, not a separate JSON response.) ``` -------------------------------- ### Iterate Over Configuration Sections Source: https://configupdater.readthedocs.io/en/latest/_modules/configparser.html Returns an iterator over the section names, including the default section. ```python def __iter__(self): # XXX does it break when underlying container state changed? return itertools.chain((self.default_section,), self._sections.keys()) ``` -------------------------------- ### Configuration Retrieval Methods Source: https://configupdater.readthedocs.io/en/latest/_modules/configparser.html Methods for retrieving configuration values with automatic type conversion. ```APIDOC ## GET /getint ### Description Retrieves a configuration value as an integer. ### Parameters #### Query Parameters - **section** (string) - Required - The section name - **option** (string) - Required - The option key - **raw** (boolean) - Optional - Whether to use raw values - **vars** (dict) - Optional - Variables for interpolation - **fallback** (any) - Optional - Default value if not found ``` ```APIDOC ## GET /getfloat ### Description Retrieves a configuration value as a float. ### Parameters #### Query Parameters - **section** (string) - Required - The section name - **option** (string) - Required - The option key - **raw** (boolean) - Optional - Whether to use raw values - **vars** (dict) - Optional - Variables for interpolation - **fallback** (any) - Optional - Default value if not found ``` ```APIDOC ## GET /getboolean ### Description Retrieves a configuration value as a boolean (0, false, no, off for False; 1, true, yes, on for True). ### Parameters #### Query Parameters - **section** (string) - Required - The section name - **option** (string) - Required - The option key - **raw** (boolean) - Optional - Whether to use raw values - **vars** (dict) - Optional - Variables for interpolation - **fallback** (any) - Optional - Default value if not found ``` -------------------------------- ### Insert Options with Comments Source: https://configupdater.readthedocs.io/en/latest/usage.html Use add_before or add_after to insert options with associated comments. ```python updater = ConfigUpdater() updater.read_string(cfg) (updater["metadata"]["summary"].add_before .comment("Ada would have loved MIT") .option("license", "MIT")) ``` ```python updater = ConfigUpdater() updater.read_string(cfg) (updater["metadata"]["author"].add_after .comment("Ada would have loved MIT") .option("license", "MIT")) ```