config.py 4.9 KB

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