config.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. #============================================================================
  2. # This file is part of Pwman3.
  3. #
  4. # Pwman3 is free software; you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License, version 2
  6. # as published by the Free Software Foundation;
  7. #
  8. # Pwman3 is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License
  14. # along with Pwman3; if not, write to the Free Software
  15. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  16. #============================================================================
  17. # Copyright (C) 2012 Oz Nahum <nahumoz@gmail.com>
  18. #============================================================================
  19. # Copyright (C) 2006 Ivan Kelly <ivan@ivankelly.net>
  20. #============================================================================
  21. import sys
  22. import os
  23. if sys.version_info.major > 2:
  24. from configparser import ConfigParser, ParsingError, NoOptionError
  25. else:
  26. from ConfigParser import ConfigParser, ParsingError, NoOptionError
  27. import copy
  28. config_dir = os.path.expanduser("~/.pwman")
  29. default_config = {'Global': {'umask': '0100', 'colors': 'yes',
  30. 'cls_timeout': '5',
  31. 'save': 'True'
  32. },
  33. 'Database': {'type': 'SQLite',
  34. 'filename': os.path.join(config_dir,
  35. "pwman.db")},
  36. 'Encryption': {'algorithm': 'AES'},
  37. 'Readline': {'history': os.path.join(config_dir,
  38. "history")}
  39. }
  40. class ConfigException(Exception):
  41. """Basic exception for config."""
  42. def __init__(self, message):
  43. self.message = message
  44. def __str__(self):
  45. return "{}: {}".format(self.__class__.__name__,
  46. self.message) # pragma: no cover
  47. class ConfigNoConfigException(ConfigException):
  48. pass
  49. _file = None
  50. _conf = dict()
  51. _defaults = dict()
  52. class Config(object):
  53. def __init__(self, filename=None, defaults=None, **kwargs):
  54. self.filename = filename
  55. self.parser = self._load(defaults)
  56. def _load(self, defaults):
  57. try:
  58. parser = ConfigParser(defaults)
  59. with open(self.filename) as f:
  60. try:
  61. parser.read_file(f)
  62. except AttributeError:
  63. parser.readfp(f)
  64. except ParsingError as e:
  65. raise ConfigException(e)
  66. self._add_defaults(defaults, parser)
  67. return parser
  68. def _add_defaults(self, defaults, parser):
  69. for section, options in defaults.items():
  70. if not parser.has_section(section):
  71. parser.add_section(section)
  72. for key, value in options.items():
  73. if not parser.has_option(section, key):
  74. parser.set(section, key, value)
  75. def get_value(self, section, name):
  76. try:
  77. return self.parser.get(section, name)
  78. except NoOptionError:
  79. return ''
  80. def set_value(self, section, name, value):
  81. self.parser.set(section, name, value)
  82. def set_conf(conf_dict):
  83. global _conf
  84. _conf = conf_dict
  85. def set_defaults(defaults):
  86. global _defaults
  87. _defaults = defaults
  88. def add_defaults(defaults):
  89. global _defaults
  90. for n in defaults.keys():
  91. if n not in _defaults:
  92. _defaults[n] = dict()
  93. for k in defaults[n].keys():
  94. _defaults[n][k] = defaults[n][k]
  95. def get_value(section, name):
  96. global _conf, _defaults
  97. try:
  98. return _conf[section][name]
  99. except KeyError:
  100. pass
  101. try:
  102. value = _defaults[section][name]
  103. set_value(section, name, value)
  104. return value
  105. except KeyError:
  106. pass
  107. return ''
  108. def set_value(section, name, value):
  109. global _conf
  110. if section not in _conf:
  111. _conf[section] = dict()
  112. _conf[section][name] = value
  113. def get_conf():
  114. """
  115. Get a copy of the config.
  116. Modifications have no effect.
  117. This function only serves for allowing applications
  118. to output the config to the user"""
  119. global _conf
  120. return copy.deepcopy(_conf)
  121. def load(filename):
  122. """Load configuration from 'filename'."""
  123. global _conf, _file
  124. _file = filename
  125. parser = ConfigParser()
  126. fp = None
  127. try:
  128. try:
  129. fp = open(filename, "r")
  130. try:
  131. parser.read_file(fp)
  132. except AttributeError:
  133. parser.readfp(fp)
  134. except ParsingError as e:
  135. raise ConfigException(e)
  136. except IOError as e:
  137. raise ConfigNoConfigException(e)
  138. finally:
  139. if (fp):
  140. fp.close()
  141. for section in parser.sections():
  142. for option in parser.options(section):
  143. set_value(section, option, parser.get(section, option))
  144. def set_config(config_dict):
  145. global _conf
  146. _conf = config_dict
  147. def save(filename=None):
  148. """Save the configuration to 'filename'."""
  149. global _conf, _file
  150. if not filename:
  151. filename = _file
  152. parser = ConfigParser()
  153. for key in _conf.keys():
  154. if not parser.has_section(key):
  155. parser.add_section(key)
  156. sectiondict = _conf[key]
  157. if isinstance(sectiondict, dict):
  158. for optionkey in sectiondict.keys():
  159. parser.set(key, optionkey, str(sectiondict[optionkey]))
  160. try:
  161. fp = open(filename, "w+")
  162. parser.write(fp)
  163. fp.close()
  164. except IOError as e:
  165. raise ConfigException(str(e))
  166. def get_pass_conf():
  167. numerics = get_value("Generator", "numerics").lower() == 'true'
  168. # TODO: allow custom leetifying through the config
  169. leetify = get_value("Generator", "leetify").lower() == 'true'
  170. special_chars = get_value("Generator", "special_chars").lower() == 'true'
  171. return numerics, leetify, special_chars