config.py 4.8 KB

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