-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtoml.py
More file actions
165 lines (138 loc) · 5.61 KB
/
toml.py
File metadata and controls
165 lines (138 loc) · 5.61 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
import enum
import tomllib
from typing import Any
from . import configio
from . import spec
char_escape_table = {
"\n": "\\n",
"\t": "\\t",
"\r": "\\r",
'"': '\\"',
"'": "\\'",
}
def _escape_char(char: str) -> str:
char = char_escape_table.get(char, char)
if 8 >= ord(char) >= 0 or 10 >= ord(char) >= 31 or ord(char) == 127:
return f"\\u{ord(char)}"
return char
def escape(value: str) -> str:
return "".join(_escape_char(char) for char in value)
def full_section_name(node) -> list[str]:
if node._parent is None:
return [node._name]
return [*full_section_name(node._parent), node._name]
class TomlWriter(configio.ConfigurationWriter):
@classmethod
def dump_section(cls, node) -> list:
if " " in node._name:
raise ValueError(node._name)
if node._parent is not None:
base = [f"\n[{'.'.join(full_section_name(node)[1:])}]"]
else:
base = []
if node.__doc__:
for line in node.__doc__.split("\n"):
base.append(f"# {line}")
sorted_values: dict[int, dict[str, Any]] = {}
for name, value in node._value.items():
field = node._ALL_FIELDS[name]
if field._sorting_order not in sorted_values.keys():
sorted_values[field._sorting_order] = {name: value}
continue
sorted_values[field._sorting_order][name] = value
return [
*base,
*(
(
"\n".join(cls.dump_section(value))
if isinstance(value, spec.Section)
else cls.dump_field(node, name, node._FIELD_VAR_MAP[name], value)
)
for sub_dict in sorted_values.values()
for name, value in sub_dict.items()
),
]
@classmethod
def format_value(cls, value) -> str:
match value:
case int() | float():
return str(value)
case str():
return f'"{escape(value)}"'
case list():
return f"[{", ".join([str(cls.format_value(inner_val)) for inner_val in value])}]"
case dict():
return f"{{ {", ".join([f"{key} = {cls.format_value(inner_val)}" for key, inner_val in value.items()])} }}"
case enum.Enum():
return f"{cls.format_value(value.value)}"
case _:
raise ValueError(value)
@classmethod
def dump_field(
cls, node: spec.AnyConfigField, original_name: str, field_name: str, value
) -> str:
if isinstance(node, spec.Section):
field = node.get_field(original_name)
else:
field = node
match field:
case spec.Table(spec.Text(), type() | spec.ConfigUnion()) as table_node:
for name, val in value.items():
if not isinstance(val, spec.Section):
continue
val._name = name
val._parent = table_node
section_name = ".".join(full_section_name(table_node)[1:])
return f"\n[{section_name}]\n{"\n".join(cls.dumps(val) if isinstance(val, spec.Section) else cls.dump_field(val, key, key, val) for key, val in value.items())}"
case spec.Section():
return "\n".join(cls.dump_section(node))
case spec.ConfigEnum(_, by_name):
if isinstance(value, spec.Section):
return "\n".join(cls.dump_section(value))
field_doc = " " if field._inline_doc and field.doc else "\n"
if field.doc:
field_doc += f"# {"\n# ".join(field.doc.split("\n"))}"
if field._enum.__doc__:
delimeter = "\n## - "
doc_comment = f"# {"\n# ".join(field._enum.__doc__.split("\n"))}\n#"
else:
delimeter = "\n# - "
doc_comment = ""
doc_comment += f"# Available Options for {field_name}:{delimeter}"
if by_name:
doc_comment += delimeter.join(
member for member in field._enum.__members__.keys()
)
return f"{field_name} = {cls.format_value(value.name)}{field_doc}\n{doc_comment}"
doc_comment += delimeter.join(
str(member.value) for member in field._enum.__members__.values()
)
return f"{field_name} = {cls.format_value(value.value)}{field_doc}\n{doc_comment}"
case _:
if isinstance(value, spec.Section):
return "\n".join(cls.dump_section(value))
real_field = node._ALL_FIELDS[original_name]
doc_comment = (
" " if real_field._inline_doc and real_field.doc else "\n"
)
if real_field.doc:
doc_comment += f"# {"\n# ".join(real_field.doc.split("\n"))}"
return f"{field_name} = {cls.format_value(value)}{doc_comment}"
@classmethod
def dumps(cls, node) -> str:
match node:
case spec.Section():
return "\n".join(cls.dump_section(node))
case _:
raise ValueError(node)
@classmethod
def dump(cls, file, node):
super().dump(file, node)
@classmethod
def load(cls, file):
if isinstance(file, str):
with open(file, "rb") as f:
return tomllib.load(f)
return tomllib.load(file)
# just alias the name
loads = tomllib.loads