config.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  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: # pragma: no cover
  24. from configparser import (ConfigParser, ParsingError, NoOptionError,
  25. NoSectionError, MissingSectionHeaderError)
  26. else: # pragma: no cover
  27. from ConfigParser import (ConfigParser, ParsingError, NoOptionError,
  28. NoSectionError, MissingSectionHeaderError)
  29. config_dir = os.path.expanduser("~/.pwman")
  30. default_config = {'Global': {'umask': '0100', 'colors': 'yes',
  31. 'cls_timeout': '10', 'cp_timeout': '5',
  32. 'save': 'True', 'supress_version_check': 'no',
  33. 'lock_timeout': '600'
  34. },
  35. 'Database': {
  36. 'dburi': 'sqlite://' + os.path.join(config_dir,
  37. 'pwman.db')},
  38. 'Readline': {'history': os.path.join(config_dir,
  39. 'history')},
  40. 'Crypto': {'supress_warning': 'no'},
  41. 'Updater': {'supress_version_check': 'no'}
  42. }
  43. if 'win' in sys.platform:
  44. default_config['Database']['dburi'] = default_config['Database']['dburi'].replace("\\", "/") # noqa
  45. class ConfigException(Exception):
  46. """Basic exception for config."""
  47. def __init__(self, message):
  48. self.message = message
  49. def __str__(self):
  50. return "{}: {}".format(self.__class__.__name__,
  51. self.message) # pragma: no cover
  52. class ConfigNoConfigException(ConfigException):
  53. pass
  54. class Config(object):
  55. def __init__(self, filename=None, defaults=None, **kwargs):
  56. self.filename = filename
  57. self.parser = self._load(defaults)
  58. def _load(self, defaults):
  59. defaults = defaults or default_config
  60. parser = ConfigParser()
  61. try:
  62. with open(self.filename) as f:
  63. try:
  64. try:
  65. parser.read_file(f)
  66. except AttributeError:
  67. parser.readfp(f)
  68. except (ParsingError, MissingSectionHeaderError) as e:
  69. raise ConfigException(e)
  70. except IOError:
  71. self._self_write_new_conf(self.filename, defaults, parser)
  72. self._add_defaults(defaults, parser)
  73. return parser
  74. def _self_write_new_conf(self, filename, defaults, parser):
  75. self.parser = parser
  76. self._add_defaults(defaults, parser)
  77. self.save()
  78. def _add_defaults(self, defaults, parser):
  79. for section, options in defaults.items():
  80. if not parser.has_section(section):
  81. parser.add_section(section)
  82. for key, value in options.items():
  83. if not parser.has_option(section, key):
  84. parser.set(section, key, value)
  85. def get_value(self, section, name):
  86. try:
  87. return self.parser.get(section, name)
  88. except (NoOptionError, NoSectionError): # pragma: no cover
  89. return ''
  90. def set_value(self, section, name, value):
  91. self.parser.set(section, name, value)
  92. def save(self):
  93. if "False" not in self.get_value("Global", "Save"):
  94. with open(self.filename, "w") as fp:
  95. self.parser.write(fp)
  96. def get_pass_conf(config):
  97. ascii_lowercase = config.get_value("Generator",
  98. "ascii_lowercase").lower() == 'true'
  99. ascii_uppercase = config.get_value("Generator",
  100. "ascii_uppercase").lower() == 'true'
  101. ascii_digits = config.get_value("Generator",
  102. "ascii_digits").lower() == 'true'
  103. ascii_punctuation = config.get_value("Generator",
  104. "ascii_punctuation").lower() == 'true'
  105. return ascii_lowercase, ascii_uppercase, ascii_digits, ascii_punctuation