blob: 5f9dd55667e63ebcf5d295050519785a98f6511f [file] [log] [blame]
Alex0989ecf2022-03-29 13:43:21 -05001# Author: Alex Savatieiev (osavatieiev@mirantis.com; a.savex@gmail.com)
2# Copyright 2019-2022 Mirantis, Inc.
Alexb151fbe2019-04-22 16:53:30 -05003import configparser
4import os
5
Alex3bc95f62020-03-05 17:00:04 -06006from . import logger_cli
Alex9a4ad212020-10-01 18:04:25 -05007from .const import truth
Alexb151fbe2019-04-22 16:53:30 -05008
9
10class ConfigFile(object):
Alexb151fbe2019-04-22 16:53:30 -050011 _config = None
12 _section_name = None
13 _config_filepath = None
14
15 def __init__(self, section_name, filepath=None):
16 self._section_name = section_name
17 self._config = configparser.ConfigParser()
18 if filepath is not None:
19 self._config_filepath = self._ensure_abs_path(filepath)
20 self._config.read(self._config_filepath)
21 else:
22 logger_cli.debug("... previous iteration conf not found")
23
24 def force_reload_config(self, path):
25 _path = self._ensure_abs_path(path)
26 self._config.read(_path)
27
28 def save_config(self, filepath=None):
29 if filepath:
30 self._config_filepath = filepath
31 with open(self._config_filepath, "w") as configfile:
32 self._config.write(configfile)
33
34 @staticmethod
35 def _ensure_abs_path(path):
36 if path.startswith('~'):
37 path = os.path.expanduser(path)
38 else:
39 # keep it safe, create var :)
40 path = path
41
42 # make sure it is absolute
43 if not os.path.isabs(path):
44 return os.path.abspath(path)
45 else:
46 return path
47
48 def _ensure_boolean(self, _value):
Alex9a4ad212020-10-01 18:04:25 -050049 if _value.lower() in truth:
Alexb151fbe2019-04-22 16:53:30 -050050 return True
51 else:
52 return False
53
54 def get_value(self, key, value_type=None):
55 if not value_type:
56 # return str by default
57 return self._config.get(self._section_name, key)
58 elif value_type == int:
59 return self._config.getint(self._section_name, key)
60 elif value_type == bool:
61 return self._config.getboolean(self._section_name, key)
62
63 def set_value(self, key, value):
64 _v = None
65 if not isinstance(value, str):
66 _v = str(value)
67 else:
68 _v = value
69
70 if self._section_name not in self._config.sections():
71 self._config.add_section(self._section_name)
72
73 self._config[self._section_name][key] = _v