-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctions.py
More file actions
103 lines (78 loc) · 2.48 KB
/
functions.py
File metadata and controls
103 lines (78 loc) · 2.48 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
import inspect
import os
import pathlib
import sys
from ruamel.yaml import YAML
yaml = YAML(typ="rt", pure=True)
yaml.preserve_quotes = True
yaml.default_flow_style = False
PATH = pathlib.Path(__file__).parent
class NamespaceMixin:
@property
def namespace(self):
return str(pathlib.Path(inspect.getfile(self.__class__)).parent).rsplit(
maxsplit=1, sep=os.sep
)[1]
def log_to_txt(text: str) -> None:
with open(PATH / "log.txt", "a") as f:
f.write(text + "\n")
def read_yaml(path: str = PATH / "settings.yaml") -> dict:
try:
with open(path, "r", encoding="utf-8") as f:
return yaml.load(f)
except FileNotFoundError:
return {}
def write_yaml(
data: dict,
path: str = PATH / "settings.yaml",
) -> None:
try:
with open(path, "w", encoding="utf-8") as f:
yaml.dump(data, f)
except Exception as e:
print(str(e))
sys.exit()
class NamespaceAlreadyExistsException(Exception): ...
def register_namespace(namespace: str) -> None:
settings = read_yaml()
print(settings)
if settings.get(namespace, None) is None:
settings[namespace] = {}
write_yaml(settings)
# else:
# raise NamespaceAlreadyExistsException(
# "Namespace already exists. Please rename your plugin."
# )
class SettingsMixin(NamespaceMixin):
def write_settings(
self, key: str, value: str, namespace: str | None = None
) -> None:
if namespace is None:
namespace = self.namespace
settings = read_yaml()
try:
settings[namespace][key] = value
except KeyError:
print("Setting not found. Please check namespace or key.")
else:
write_yaml(settings)
def read_settings(self, key: str, namespace: str | None = None) -> any:
if namespace is None:
namespace = self.namespace
settings = read_yaml()
try:
value = settings.get(namespace).get(key)
except AttributeError:
print("Setting not found. Please check namespace or key.")
else:
return value
def search_key(self, key) -> any:
return _search_key(read_yaml(), key)
def _search_key(dictionary, key):
if key in dictionary:
return dictionary[key]
for value in dictionary.values():
if isinstance(value, dict):
if _search_key(value, key):
return value[key]
return False