-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathconfig.py
More file actions
156 lines (132 loc) · 5.31 KB
/
Copy pathconfig.py
File metadata and controls
156 lines (132 loc) · 5.31 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
from typing import Any
import re
from pathlib import Path
from fa_paths import CONFIG
import config_autogenerated
class Config_Missing(ValueError):
pass
class Conf_Editor:
def __init__(self) -> None:
self.unsaved = False
self.inContexts = 0
def __load(self):
if self.unsaved:
raise RuntimeError("Unsaved Changes")
if not self.inContexts:
raise RuntimeError("Not in context")
section = ""
self.c = (c := {section: ""})
with CONFIG().open(newline="", encoding="utf8") as fp:
for line in fp:
if m := re.match(r"(?m)^[ \t]*\[([^\r\n\]]+)\]", line):
section = m.group(1)
c[section] = ""
c[section] += line
def setting(self, setting):
return rf"(?m)^[ \t]*{setting}[ \t]*=(.*)$"
def commented_setting(self, setting):
return rf"(?m)^[ \t]*;[ \t]*{setting}[ \t]*=(.*)$"
def get_setting(self, section, setting):
if not self.inContexts:
raise RuntimeError("Not in context")
if section not in self.c:
self.c[section] = f"[{section}]\n"
if m := re.search(self.setting(setting), self.c[section]):
return m.group(1).strip()
if m := re.search(self.commented_setting(setting), self.c[section]):
return m.group(1).strip()
raise Config_Missing(f"No {setting} setting found in {section} section.")
def set_setting(self, sec, setting, value, force=False):
if not self.inContexts:
raise RuntimeError("Not in context")
self.unsaved = True
set_string = f"{setting}={value.strip()}"
(self.c[sec], n) = re.subn(self.setting(setting), set_string, self.c[sec])
if n == 1:
return
if n > 1:
raise ValueError(f"Duplicate setting [{setting}] found in section [{sec}]")
cs = self.commented_setting(setting)
(self.c[sec], n) = re.subn(cs, set_string, self.c[sec], count=1)
if n == 0:
if not force:
raise Config_Missing(
f"Setting [{setting}] not found in section [{sec}]"
)
self.c[sec] += set_string + "\n"
def toggle(self, section, setting):
val = self.get_setting(section, setting)
val = "true" if val == "false" else "false"
self.set_setting(section, setting, val)
return 0
def __save(self):
if not self.inContexts:
raise RuntimeError("Not in context")
with CONFIG().open("w", newline="", encoding="utf8") as fp:
for section in self.c.values():
fp.write(section)
self.unsaved = False
def __enter__(self):
self.inContexts += 1
if self.inContexts == 1:
self.__load()
return config_autogenerated.main(self)
def __exit__(self, exc_type, exc_val, exc_tb):
if self.inContexts <= 0:
raise RuntimeError("Unbalanced context manager calls")
if self.inContexts == 1:
if self.unsaved:
self.__save()
self.inContexts -= 1
def __del__(self):
if self.unsaved:
raise RuntimeError("Unsaved Changes")
def __remake_section_names():
from contextlib import redirect_stdout
with current_conf:
c = current_conf
print(c.c.keys())
with open("config_autogenerated.py", "w") as fp:
with redirect_stdout(fp):
print(
f"#file autogenerated by {Path(__file__).stem}.{__remake_section_names.__name__}"
)
print("from config_helper import base_settings as __bs")
print("")
print("#cSpell:disable")
print("")
print("")
for k, text in c.c.items():
class_name = k.replace("-", "_")
if not class_name:
if m := re.search(r"\bversion=(.*)", text):
print(f"version={int(m.group(1))}")
continue
print(f"class _{class_name}(__bs):")
for line in text.splitlines():
if m := re.match(r"[ \t]*;?[ \t]*([\w-]+)[ \t]*=", line):
setting = m.group(1).replace("-", "_")
print(f" {setting}: str")
print(" pass")
print("")
print("")
print("class main(object):")
print(" def __init__(self,conf):")
for k in c.c.keys():
class_name = k.replace("-", "_")
if not class_name:
continue
print(f" self.{class_name} = _{class_name}('{k}', conf)")
current_conf = Conf_Editor()
# with current_conf:
# conf_ver=int(current_conf.get_setting("","version"))
# if version < conf_ver:
# print(f"Newer conf.ini version [{conf_ver}] detected. Please inform Factorio-Access maintainers.")
if __name__ == "__main__":
__remake_section_names()
with current_conf as test:
print(test.multiplayer_lobby.visibility_steam)
# print(sound.alerts_volume)
# sound.alerts_volume='0.65'
# print(sound.alerts_volume)
# current_conf.save()