diff options
Diffstat (limited to 'src/sliceitoff/settings/settings.py')
-rw-r--r-- | src/sliceitoff/settings/settings.py | 82 |
1 files changed, 82 insertions, 0 deletions
diff --git a/src/sliceitoff/settings/settings.py b/src/sliceitoff/settings/settings.py new file mode 100644 index 0000000..cf588b7 --- /dev/null +++ b/src/sliceitoff/settings/settings.py @@ -0,0 +1,82 @@ +""" settings.settings - handles settings reading, updating and writing """ +import os +from pathlib import Path +from .static import DEFAULT_SETTINGS + +class Settings: + def __init__(self, filename = None): + self.settings=[] + if filename: + self.config_filename = filename + else: + if os.name == 'nt': + self.config_filename = (Path.home().resolve() + .joinpath('sliceitoff.cfg')) + else: + self.config_filename = (Path.home().resolve() + .joinpath('.config').joinpath('sliceitoffrc')) + if not self.config_filename.is_file(): + self.settings=DEFAULT_SETTINGS[:] + return + with open(self.config_filename, "r", encoding="utf-8") as config_file: + for line in config_file: + entry = self.validate_line(line) + if not entry: + continue + self.settings.append(entry) + + def validate_line(self, line): + if not line or line[0] == '#': + return None + data = line.split('=') + if len(data) != 2: + return None + return data[0], data[1] + + def get_values(self, option): + return [x[1] for x in self.settings if x[0]==option] + + def put_values(self, option, values): + for x in values: + self.put_value(option, x) + + def remove_values(self, option): + for x in self.settings[:]: + if x[0]==option: + self.settings.remove(x) + + def replace_values(self, option, values): + self.remove_values(option) + self.put_values(option, values) + + def get_value(self, option): + v = self.get_values(option) + if not v: + return None + return v + + def get_value_or_default(self, option): + v = self.get_values(option) + if v: + return v + return [x[1] for x in DEFAULT_SETTINGS if x[0]==option][1] + + def put_value(self, option, value): + self.settings.append((option, value)) + + def replace_value(self, option, value): + self.remove_values(option) + self.put_value(option, value) + + def save(self): + with open(self.config_filename, 'w', encoding="utf-8") as config_file: + for option, value in self.settings: + config_file.write(f"{option}={value}\n") + +# Initialize only one time +try: + # pylint: disable = used-before-assignment + # This is intented behaviour + settings +except NameError: + settings = Settings() |