geändert: .gitignore
geändert: README.md geändert: pyproject.toml geändert: src/config_parser/__init__.py neue Datei: src/config_parser/_configuration.py neue Datei: src/config_parser/exceptions.py neue Datei: src/config_parser/ini.py neue Datei: src/config_parser/json.py neue Datei: src/config_parser/parse/ini.py neue Datei: src/config_parser/parse/json.py neue Datei: tests/ini/test_ini.py neue Datei: tests/json/test.json neue Datei: tests/json/test_json.py neue Datei: tests/json/test_parser.py neue Datei: tests/test_configuration_class.py
This commit is contained in:
@@ -1,49 +1,14 @@
|
||||
QUOTATION_MARKS = {'"', '\''}
|
||||
KEY_VALUE_LINE = 0
|
||||
GROUP_HEADER_LINE = 1
|
||||
COMMENT_LINE = 2
|
||||
'''
|
||||
A library for parsing configuration files in various formats.
|
||||
|
||||
def reverse_dict(d):
|
||||
return {k: v for k, v in list(reversed(d.items()))}
|
||||
Modules:
|
||||
- configuration: Base classes.
|
||||
- ini: INI file parser and serializer.
|
||||
- exceptions: Custom exceptions for configuration parsing.
|
||||
'''
|
||||
|
||||
def parse_key_value_line(line):
|
||||
if '=' not in line:
|
||||
return {'': ''}
|
||||
return {line.split('=')[0].strip(): '='.join(line.split('=')[1:]).strip()}
|
||||
from ._configuration import Configuration
|
||||
|
||||
|
||||
def parse_group_header(line):
|
||||
if line.startswith('[') and line.endswith(']'):
|
||||
return line[1:-1]
|
||||
|
||||
|
||||
def parse_line_type(line):
|
||||
line = line.strip()
|
||||
if line.startswith('#'):
|
||||
return COMMENT_LINE
|
||||
if line.startswith('[') and line.endswith(']'):
|
||||
return GROUP_HEADER_LINE
|
||||
if '=' in line:
|
||||
return KEY_VALUE_LINE
|
||||
|
||||
def compress_conf(conf):
|
||||
while '\n\n' in conf:
|
||||
conf = conf.replace('\n\n', '\n')
|
||||
return conf.strip()
|
||||
|
||||
def parse_ini(conf):
|
||||
'''Parses INI configuration from a string and returns a nested dictionary.'''
|
||||
|
||||
conf = compress_conf(conf)
|
||||
result = {}
|
||||
current_group = {}
|
||||
for line in list(reversed(conf.split('\n'))):
|
||||
line = line.strip()
|
||||
if parse_line_type(line) == COMMENT_LINE:
|
||||
continue
|
||||
if parse_line_type(line) == GROUP_HEADER_LINE:
|
||||
result[parse_group_header(line)] = reverse_dict(current_group)
|
||||
current_group = {}
|
||||
if parse_line_type(line) == KEY_VALUE_LINE:
|
||||
current_group = current_group | parse_key_value_line(line)
|
||||
return reverse_dict(result)
|
||||
__all__ = [
|
||||
'Configuration'
|
||||
]
|
||||
Reference in New Issue
Block a user