]> andersk Git - sql.git/blobdiff - lib/python/mitsql/config.py
implemented base interface
[sql.git] / lib / python / mitsql / config.py
diff --git a/lib/python/mitsql/config.py b/lib/python/mitsql/config.py
new file mode 100644 (file)
index 0000000..4c8e3f0
--- /dev/null
@@ -0,0 +1,83 @@
+"""
+Global configuration objects.
+
+Joe Presbrey  <presbrey@mit.edu>
+"""
+
+from ConfigParser import ConfigParser, NoSectionError, NoOptionError
+import os
+
+_ENV_BASE='_SQL_MIT_EDU'
+
+class Section(object):
+    """Configuration section namespace."""
+    def __init__(self, d):
+        self.items = d
+
+    def __getattr__(self, k):
+        v = self.items.get(k, None)
+        try:
+            if str(int(v)) == str(v): v = int(v)
+        except TypeError: pass
+        except ValueError: pass
+        try:
+            if str(v).lower() == 'true': v = True
+            if str(v).lower() == 'false': v = False
+        except TypeError: pass
+        except ValueError: pass
+        return v
+
+    def __iter__(self):
+        return iter(self.items)
+
+    def __str__(self):
+        return str(self.items)
+
+class Config(object):
+    """Base configuration namespace."""
+    def __init__(self, filename, *args, **kwargs):
+        self._cp = ConfigParser(*args, **kwargs)
+        self.read(filename)
+        self._none = Section({})
+    
+    def _samefile(self, f1, f2):
+        try:
+            return os.path.samefile(f1, f2)
+        except OSError, e:
+            return False
+    
+    def read(self, filename):
+        config_path = [os.path.join(x, filename) for x in [
+            os.path.dirname(__file__),
+            '/etc']]
+        if _ENV_BASE in os.environ:
+            config_path.insert(1, os.path.join(os.environ[_ENV_BASE], 'etc', filename))
+        def append(path):
+            r = os.path.join(path, filename)
+            if not r in config_path:
+                config_path.append(r)
+        if 'HOME' in os.environ:
+            append(os.environ['HOME'])
+        if 'PWD' in os.environ:
+            append(os.environ['PWD'])
+        self._cp.read(config_path)
+        self._sections = dict(map(lambda x: (x, Section(dict(self._cp.items(x)))),
+                                  self._cp.sections()))
+    
+    def get(self, *av, **kw):
+        try: return self._cp.get(*av, **kw)
+        except NoSectionError: return None
+        except NoOptionError: return None
+    
+    def __getattr__(self, k):
+        return self._sections.get(k, self._none)
+    
+    def __str__(self):
+        d = {}
+        for x in self._cp.sections():
+            d[x] = dict(self._cp.items(x))
+        return str(d)
+
+if __name__ == '__main__':
+    import mitsql
+    print mitsql.config
This page took 0.03559 seconds and 4 git commands to generate.