from .util import validate_url, validate_list from os import getcwd, path from typing import List import json CONFIG_FILE = "ups.json" class config: def __init__(self, dir="") -> None: if dir == "": dir = getcwd() self.path = path.join(dir, CONFIG_FILE) self.conf = {} self.load() # load the configuration from the file def load(self) -> None: try: f = open(self.path, "r") content = f.read() f.close() except Exception as e: raise Exception("failed to read config: %s" % e) else: self.conf = json.loads(content) f.close() # save the current configuration def save(self) -> None: content = json.dumps(self.conf, indent=2) try: f = open(self.path, "w") f.write(content) f.close() except Exception as e: raise Exception("failed to save config: %s" % e) # set a URL key in the configuration def set_url(self, key: str, val: str) -> None: if not validate_url(val): raise Exception("expected a valid URL for %s" % key) self.conf[key] = val self.save() # set a string key in the configuration def set_str(self, key: str, val: str) -> None: if val == "" or val is None: raise Exception("expected a non-empty string for %s" % key) self.conf[key] = val self.save() def set_list(self, key: str, val: List[str]) -> None: if not validate_list(val): raise Exception("expected a non-empty list for %s" % key) self.conf[key] = val self.save() # read a URL key from the configuration def url(self, key: str) -> str: if key not in self.conf.keys() or not validate_url(self.conf[key]): return "" return self.conf[key] # read a string key from the configuration file def str(self, key: str) -> str: if key not in self.conf.keys(): return "" return self.conf[key] # read a list from the configuration file def list(self, key: str) -> List[str]: if key not in self.conf.keys() or not validate_list(self.conf[key]): return [] return self.conf[key]