config.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  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
  25. else:
  26. from ConfigParser import ConfigParser, ParsingError
  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. return self.parser.get(section, name)
  77. def set_value(self, section, name, value):
  78. self.parser.set(section, name, value)
  79. def set_conf(conf_dict):
  80. global _conf
  81. _conf = conf_dict
  82. def set_defaults(defaults):
  83. global _defaults
  84. _defaults = defaults
  85. def add_defaults(defaults):
  86. global _defaults
  87. for n in defaults.keys():
  88. if n not in _defaults:
  89. _defaults[n] = dict()
  90. for k in defaults[n].keys():
  91. _defaults[n][k] = defaults[n][k]
  92. def get_value(section, name):
  93. global _conf, _defaults
  94. try:
  95. return _conf[section][name]
  96. except KeyError:
  97. pass
  98. try:
  99. value = _defaults[section][name]
  100. set_value(section, name, value)
  101. return value
  102. except KeyError:
  103. pass
  104. return ''
  105. def set_value(section, name, value):
  106. global _conf
  107. if section not in _conf:
  108. _conf[section] = dict()
  109. _conf[section][name] = value
  110. def get_conf():
  111. """
  112. Get a copy of the config.
  113. Modifications have no effect.
  114. This function only serves for allowing applications
  115. to output the config to the user"""
  116. global _conf
  117. return copy.deepcopy(_conf)
  118. def load(filename):
  119. """Load configuration from 'filename'."""
  120. global _conf, _file
  121. _file = filename
  122. parser = ConfigParser()
  123. fp = None
  124. try:
  125. try:
  126. fp = open(filename, "r")
  127. try:
  128. parser.read_file(fp)
  129. except AttributeError:
  130. parser.readfp(fp)
  131. except ParsingError as e:
  132. raise ConfigException(e)
  133. except IOError as e:
  134. raise ConfigNoConfigException(e)
  135. finally:
  136. if (fp):
  137. fp.close()
  138. for section in parser.sections():
  139. for option in parser.options(section):
  140. set_value(section, option, parser.get(section, option))
  141. def set_config(config_dict):
  142. global _conf
  143. _conf = config_dict
  144. def save(filename=None):
  145. """Save the configuration to 'filename'."""
  146. global _conf, _file
  147. if not filename:
  148. filename = _file
  149. parser = ConfigParser()
  150. for key in _conf.keys():
  151. if not parser.has_section(key):
  152. parser.add_section(key)
  153. sectiondict = _conf[key]
  154. if isinstance(sectiondict, dict):
  155. for optionkey in sectiondict.keys():
  156. parser.set(key, optionkey, str(sectiondict[optionkey]))
  157. try:
  158. fp = open(filename, "w+")
  159. parser.write(fp)
  160. fp.close()
  161. except IOError as e:
  162. raise ConfigException(str(e))
  163. def get_pass_conf():
  164. numerics = get_value("Generator", "numerics").lower() == 'true'
  165. # TODO: allow custom leetifying through the config
  166. leetify = get_value("Generator", "leetify").lower() == 'true'
  167. special_chars = get_value("Generator", "special_chars").lower() == 'true'
  168. return numerics, leetify, special_chars