Alex | b151fbe | 2019-04-22 16:53:30 -0500 | [diff] [blame] | 1 | import configparser |
| 2 | import os |
| 3 | |
Alex | 3bc95f6 | 2020-03-05 17:00:04 -0600 | [diff] [blame^] | 4 | from . import logger_cli |
Alex | b151fbe | 2019-04-22 16:53:30 -0500 | [diff] [blame] | 5 | |
| 6 | |
| 7 | class ConfigFile(object): |
| 8 | _truth = ['true', '1', 't', 'y', 'yes', 'yeah', 'yup', |
| 9 | 'certainly', 'uh-huh'] |
| 10 | _config = None |
| 11 | _section_name = None |
| 12 | _config_filepath = None |
| 13 | |
| 14 | def __init__(self, section_name, filepath=None): |
| 15 | self._section_name = section_name |
| 16 | self._config = configparser.ConfigParser() |
| 17 | if filepath is not None: |
| 18 | self._config_filepath = self._ensure_abs_path(filepath) |
| 19 | self._config.read(self._config_filepath) |
| 20 | else: |
| 21 | logger_cli.debug("... previous iteration conf not found") |
| 22 | |
| 23 | def force_reload_config(self, path): |
| 24 | _path = self._ensure_abs_path(path) |
| 25 | self._config.read(_path) |
| 26 | |
| 27 | def save_config(self, filepath=None): |
| 28 | if filepath: |
| 29 | self._config_filepath = filepath |
| 30 | with open(self._config_filepath, "w") as configfile: |
| 31 | self._config.write(configfile) |
| 32 | |
| 33 | @staticmethod |
| 34 | def _ensure_abs_path(path): |
| 35 | if path.startswith('~'): |
| 36 | path = os.path.expanduser(path) |
| 37 | else: |
| 38 | # keep it safe, create var :) |
| 39 | path = path |
| 40 | |
| 41 | # make sure it is absolute |
| 42 | if not os.path.isabs(path): |
| 43 | return os.path.abspath(path) |
| 44 | else: |
| 45 | return path |
| 46 | |
| 47 | def _ensure_boolean(self, _value): |
| 48 | if _value.lower() in self._truth: |
| 49 | return True |
| 50 | else: |
| 51 | return False |
| 52 | |
| 53 | def get_value(self, key, value_type=None): |
| 54 | if not value_type: |
| 55 | # return str by default |
| 56 | return self._config.get(self._section_name, key) |
| 57 | elif value_type == int: |
| 58 | return self._config.getint(self._section_name, key) |
| 59 | elif value_type == bool: |
| 60 | return self._config.getboolean(self._section_name, key) |
| 61 | |
| 62 | def set_value(self, key, value): |
| 63 | _v = None |
| 64 | if not isinstance(value, str): |
| 65 | _v = str(value) |
| 66 | else: |
| 67 | _v = value |
| 68 | |
| 69 | if self._section_name not in self._config.sections(): |
| 70 | self._config.add_section(self._section_name) |
| 71 | |
| 72 | self._config[self._section_name][key] = _v |