Procházet zdrojové kódy

Add config wrapper class

This will enable us to create a config instance,
which is WAY better than the horrible global config.

WAY better: easier testing and debugging ...
oz123 před 10 roky
rodič
revize
cc3f4ee781
2 změnil soubory, kde provedl 60 přidání a 0 odebrání
  1. 1 0
      pwman/data/factory.py
  2. 59 0
      pwman/util/config.py

+ 1 - 0
pwman/data/factory.py

@@ -42,6 +42,7 @@ class FactoryException(Exception):
     def __str__(self):
         return self.message
 
+
 def check_db_version(type):
     if type == "SQLite":
         ver = sqlite.check_db_version()

+ 59 - 0
pwman/util/config.py

@@ -19,6 +19,7 @@
 # Copyright (C) 2006 Ivan Kelly <ivan@ivankelly.net>
 #============================================================================
 import sys
+import os
 
 if sys.version_info.major > 2:
     from configparser import ConfigParser, ParsingError
@@ -26,6 +27,20 @@ else:
     from ConfigParser import ConfigParser, ParsingError
 import copy
 
+config_dir = os.path.expanduser("~/.pwman")
+
+default_config = {'Global': {'umask': '0100', 'colors': 'yes',
+                             'cls_timeout': '5',
+                             'save': 'True'
+                             },
+                  'Database': {'type': 'SQLite',
+                               'filename': os.path.join(config_dir,
+                                                        "pwman.db")},
+                  'Encryption': {'algorithm': 'AES'},
+                  'Readline': {'history': os.path.join(config_dir,
+                                                       "history")}
+                  }
+
 
 class ConfigException(Exception):
     """Basic exception for config."""
@@ -44,6 +59,49 @@ _file = None
 _conf = dict()
 _defaults = dict()
 
+"""
+Add a global wide defaults, without regarding any section!
+"""
+defaults = {}
+
+
+class Config(object):
+
+    def __init__(self, filename=None, defaults=None, **kwargs):
+
+        self.filename = filename
+        self.parser = self._load(defaults)
+
+    def _load(self, defaults):
+        try:
+            parser = ConfigParser(defaults)
+            with open(self.filename) as f:
+                try:
+                    parser.read_file(f)
+                except AttributeError:
+                    parser.readfp(f)
+        except ParsingError as e:
+            raise ConfigException(e)
+
+        self._add_defaults(defaults, parser)
+
+        return parser
+
+    def _add_defaults(self, defaults, parser):
+        for section, options in defaults.items():
+            if not parser.has_section(section):
+                parser.add_section(section)
+
+            for key, value in options.items():
+                if not parser.has_option(section, key):
+                    parser.set(section, key, value)
+
+    def get_value(self, section, name):
+        return self.parser.get(section, name)
+
+    def set_value(self, section, name, value):
+        self.parser.set(section, name, value)
+
 
 def set_conf(conf_dict):
     global _conf
@@ -153,6 +211,7 @@ def save(filename=None):
     except IOError as e:
         raise ConfigException(str(e))
 
+
 def get_pass_conf():
     numerics = get_value("Generator", "numerics").lower() == 'true'
     # TODO: allow custom leetifying through the config