2019-12-07 10:42:43 +00:00
|
|
|
import collections, configparser, os, typing
|
2016-03-29 11:56:58 +00:00
|
|
|
|
|
|
|
class Config(object):
|
2020-01-30 11:50:40 +00:00
|
|
|
def __init__(self, name: str, location: str):
|
|
|
|
self._name = name
|
2018-09-27 10:07:29 +00:00
|
|
|
self.location = location
|
2019-12-07 10:50:50 +00:00
|
|
|
self._config: typing.Dict[str, str] = collections.OrderedDict()
|
2019-12-07 10:42:43 +00:00
|
|
|
|
|
|
|
def _parser(self) -> configparser.ConfigParser:
|
2019-12-07 10:50:50 +00:00
|
|
|
return configparser.ConfigParser()
|
2016-03-29 11:56:58 +00:00
|
|
|
|
2018-09-28 15:51:36 +00:00
|
|
|
def load(self):
|
2018-09-27 10:07:29 +00:00
|
|
|
if os.path.isfile(self.location):
|
|
|
|
with open(self.location) as config_file:
|
2019-12-07 10:42:43 +00:00
|
|
|
parser = self._parser()
|
2018-07-15 23:36:52 +00:00
|
|
|
parser.read_string(config_file.read())
|
2019-12-07 10:42:43 +00:00
|
|
|
self._config.clear()
|
2020-01-30 11:50:40 +00:00
|
|
|
for k, v in parser[self._name].items():
|
2019-12-07 10:42:43 +00:00
|
|
|
if v:
|
|
|
|
self._config[k] = v
|
|
|
|
|
|
|
|
def save(self):
|
|
|
|
with open(self.location, "w") as config_file:
|
|
|
|
parser = self._parser()
|
2020-01-30 11:50:40 +00:00
|
|
|
parser[self._name] = self._config.copy()
|
2019-12-07 10:42:43 +00:00
|
|
|
parser.write(config_file)
|
2018-09-28 15:51:36 +00:00
|
|
|
|
2018-10-30 14:58:48 +00:00
|
|
|
def __getitem__(self, key: str) -> typing.Any:
|
2018-09-28 15:51:36 +00:00
|
|
|
return self._config[key]
|
2019-12-07 10:51:04 +00:00
|
|
|
def __setitem__(self, key: str, value: str):
|
|
|
|
self._config[key] = value
|
2019-12-07 11:05:13 +00:00
|
|
|
def __delitem__(self, key: str):
|
|
|
|
self._config.__delitem__(key)
|
|
|
|
def __contains__(self, key: str) -> bool:
|
|
|
|
return key in self._config
|
2019-12-07 10:51:04 +00:00
|
|
|
|
2018-10-30 14:58:48 +00:00
|
|
|
def get(self, key: str, default: typing.Any=None) -> typing.Any:
|
2018-09-28 15:51:36 +00:00
|
|
|
return self._config.get(key, default)
|
|
|
|
|
2019-12-07 11:05:32 +00:00
|
|
|
def get_list(self, key: str):
|
|
|
|
if key in self and self[key]:
|
|
|
|
return [item.strip() for item in self[key].split(",")]
|
|
|
|
return []
|
|
|
|
def set_list(self, key: str, list: typing.List[str]):
|
|
|
|
value = ",".join(item.strip() for item in list)
|
|
|
|
if value:
|
|
|
|
self[key] = value
|
|
|
|
elif key in self:
|
|
|
|
del self[key]
|