Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1import configparser 

2import os 

3 

4from . import logger_cli 

5 

6 

7class 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