blob: 513e0ec28d7ebba0ea07df5e45c9df60fc862bbd [file] [log] [blame]
Alexb151fbe2019-04-22 16:53:30 -05001import configparser
2import os
3
Alex3bc95f62020-03-05 17:00:04 -06004from . import logger_cli
Alex9a4ad212020-10-01 18:04:25 -05005from .const import truth
Alexb151fbe2019-04-22 16:53:30 -05006
7
8class ConfigFile(object):
Alexb151fbe2019-04-22 16:53:30 -05009 _config = None
10 _section_name = None
11 _config_filepath = None
12
13 def __init__(self, section_name, filepath=None):
14 self._section_name = section_name
15 self._config = configparser.ConfigParser()
16 if filepath is not None:
17 self._config_filepath = self._ensure_abs_path(filepath)
18 self._config.read(self._config_filepath)
19 else:
20 logger_cli.debug("... previous iteration conf not found")
21
22 def force_reload_config(self, path):
23 _path = self._ensure_abs_path(path)
24 self._config.read(_path)
25
26 def save_config(self, filepath=None):
27 if filepath:
28 self._config_filepath = filepath
29 with open(self._config_filepath, "w") as configfile:
30 self._config.write(configfile)
31
32 @staticmethod
33 def _ensure_abs_path(path):
34 if path.startswith('~'):
35 path = os.path.expanduser(path)
36 else:
37 # keep it safe, create var :)
38 path = path
39
40 # make sure it is absolute
41 if not os.path.isabs(path):
42 return os.path.abspath(path)
43 else:
44 return path
45
46 def _ensure_boolean(self, _value):
Alex9a4ad212020-10-01 18:04:25 -050047 if _value.lower() in truth:
Alexb151fbe2019-04-22 16:53:30 -050048 return True
49 else:
50 return False
51
52 def get_value(self, key, value_type=None):
53 if not value_type:
54 # return str by default
55 return self._config.get(self._section_name, key)
56 elif value_type == int:
57 return self._config.getint(self._section_name, key)
58 elif value_type == bool:
59 return self._config.getboolean(self._section_name, key)
60
61 def set_value(self, key, value):
62 _v = None
63 if not isinstance(value, str):
64 _v = str(value)
65 else:
66 _v = value
67
68 if self._section_name not in self._config.sections():
69 self._config.add_section(self._section_name)
70
71 self._config[self._section_name][key] = _v