refactored for easier testing

This commit is contained in:
2025-05-08 13:27:25 +02:00
parent 8125d88695
commit 2a25111c0a

View File

@@ -1,11 +1,12 @@
import configparser
import os import os
from configparser import ConfigParser from configparser import ConfigParser, DuplicateSectionError
class Config: class Config:
parser: ConfigParser parser: ConfigParser
def __init__(self): def __init__(self, path: str = None, filename: str = "config.ini"):
""" """
Config parser reading config.ini Config parser reading config.ini
@@ -14,12 +15,18 @@ class Config:
self.__filename: Path and name to the config file self.__filename: Path and name to the config file
""" """
self.parser = ConfigParser() self.parser = ConfigParser()
self.path = path
self.filename = filename
if self.path is None:
home_path = os.environ["HOME"] home_path = os.environ["HOME"]
full_path = os.path.join(home_path, ".config", "brovski-adress-etiketten" ) full_path = os.path.join(home_path, ".config", "brovski-adress-etiketten" )
else:
full_path = self.path
if not os.path.exists(full_path): if not os.path.exists(full_path):
os.makedirs(full_path) os.makedirs(full_path)
self.config_file = os.path.join(full_path, "config.ini") self.config_file = os.path.join(full_path, self.filename)
self._load() self._load()
@@ -32,11 +39,15 @@ class Config:
def add_section(self, section): def add_section(self, section):
self._load() self._load()
try:
self.parser.add_section(section) self.parser.add_section(section)
except DuplicateSectionError:
pass
self._save() self._save()
def set(self, section: str, option: str, value: str): def set(self, section: str, option: str, value: str):
self._load() self._load()
self.add_section(section)
self.parser.set(section, option, value) self.parser.set(section, option, value)
self._save() self._save()