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

1"""Tools to deal with ini config files.""" 

2 

3import configparser 

4import io 

5 

6 

7def from_paths(*paths: str) -> dict: 

8 """Merges the key-value pairs of `.ini` files into a dictionary. 

9 

10 Args: 

11 paths: Paths to `.ini` files. 

12 

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 

19 

20 for path in paths: 

21 cc.read(path) 

22 

23 for sec in cc.sections(): 

24 for opt in cc.options(sec): 

25 opts[sec + '.' + opt] = cc.get(sec, opt) 

26 

27 return opts 

28 

29 

30def to_string(d: dict) -> str: 

31 """Converts key-value pairs in a dictionary to a string grouped in sections. 

32 

33 Args: 

34 d: Key-value pairs. 

35 

36 Returns: 

37 String formatted like `.ini` files. 

38 """ 

39 cc = configparser.ConfigParser() 

40 

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) 

46 

47 with io.StringIO() as fp: 

48 cc.write(fp, space_around_delimiters=False) 

49 return fp.getvalue()