This repository has been archived by the owner on Jul 10, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cfgparser.py
73 lines (51 loc) · 2.04 KB
/
cfgparser.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#! /usr/bin/env python3
"""Small reader and writer for shell-esque configurations strings or files."""
from ast import literal_eval
class RawString(str):
"""Wrapper around the `str` class to specify that it is a raw string."""
def __repr__(self):
return "\"" + self + "\""
def _reads(string):
"""Read a configuration string. Returns a list of (key, value) pairs."""
content = []
for line in string.strip().splitlines():
line = line.split("=", 1)
line = [line[0].strip(), line[1].strip()]
if line[1].lower() in ("", "none"):
line[1] = None
elif line[1].startswith("'") and line[1].endswith("'"):
line[1] = RawString(literal_eval(line[1]))
else:
try:
line[1] = literal_eval(line[1])
except ValueError:
pass
content.append(line)
return content
def reads(string):
"""Read a configuration string. Returns a dictionary."""
return dict(_reads(string))
def read(file_path):
"""Read a configuration file. Returns a dictionary."""
with open(file_path, "r") as config_file:
return reads(config_file.read())
def dumps(config, padding=0):
"""Dump a configuration dictionary to a string."""
content = ""
for (key, value) in config.items():
if value is None:
value = ""
elif type(value) is RawString:
value = "'" + str(value) + "'"
else:
value = repr(value)
if value.startswith("'") and value.endswith("'"):
value = "\"" + value[1:-1] + "\""
content += "{key}{padding}={padding}{value}\n".format(key=str(key).strip(),
value=value,
padding=" " * padding)
return content
def dump(config, file_path, padding=0):
"""Dump a configuration dictionary to a file."""
with open(file_path, "w") as config_file:
config_file.write(dumps(config, padding))