config.py 4.9 KB

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