Coverage for gws-app/gws/lib/inifile/__init__.py: 0%
22 statements
« prev ^ index » next coverage.py v7.8.0, created at 2025-04-17 01:37 +0200
« prev ^ index » next coverage.py v7.8.0, created at 2025-04-17 01:37 +0200
1"""Tools to deal with ini config files."""
3import configparser
4import io
7def from_paths(*paths: str) -> dict:
8 """Merges the key-value pairs of `.ini` files into a dictionary.
10 Args:
11 paths: Paths to `.ini` files.
13 Returns:
14 Dictionary containing all the key-value pairs with the sections as prefixes.
15 """
16 opts = {}
17 cc = configparser.ConfigParser()
18 cc.optionxform = str
20 for path in paths:
21 cc.read(path)
23 for sec in cc.sections():
24 for opt in cc.options(sec):
25 opts[sec + '.' + opt] = cc.get(sec, opt)
27 return opts
30def to_string(d: dict) -> str:
31 """Converts key-value pairs in a dictionary to a string grouped in sections.
33 Args:
34 d: Key-value pairs.
36 Returns:
37 String formatted like `.ini` files.
38 """
39 cc = configparser.ConfigParser()
41 for k, v in d.items():
42 sec, _, name = k.partition('.')
43 if not cc.has_section(sec):
44 cc.add_section(sec)
45 cc.set(sec, name, v)
47 with io.StringIO() as fp:
48 cc.write(fp, space_around_delimiters=False)
49 return fp.getvalue()