Browse Source

Add basic config mechanism

Alois Mahdal 10 years ago
parent
commit
9f176b5235
1 changed files with 48 additions and 0 deletions
  1. 48
    0
      include/sardine.py

+ 48
- 0
include/sardine.py View File

4
 import os
4
 import os
5
 import sys
5
 import sys
6
 
6
 
7
+import yaml
8
+
7
 
9
 
8
 class PluginError(Exception):
10
 class PluginError(Exception):
9
     pass
11
     pass
13
     pass
15
     pass
14
 
16
 
15
 
17
 
18
+class ConfigError(Exception):
19
+
20
+    def __init__(self, path, key):
21
+        self.path = path
22
+        self.key = key
23
+
24
+    def __str__(self):
25
+        return "invalid key: %r in %s" % (self.key, self.path)
26
+
27
+
28
+class Config(object):
29
+
30
+    def __init__(self, paths, valid_keys):
31
+        self._valid_keys = valid_keys
32
+        for path in paths:
33
+            self.load(path)
34
+
35
+    def __str__(self):
36
+        ss = ["  %s: %s" % (vk, getattr(self, vk))
37
+              for vk in self._valid_keys]
38
+        return "\n".join(ss)
39
+
40
+    def load(self, path):
41
+        try:
42
+            with open(path) as fh:
43
+                conf = yaml.load(fh)
44
+        except IOError:
45
+            pass
46
+        else:
47
+            for key in conf.keys():
48
+                if key in self._valid_keys:
49
+                    setattr(self, key, conf[key])
50
+                else:
51
+                    raise ConfigError(path, key)
52
+
53
+
16
 class XGPRenderer(object):
54
 class XGPRenderer(object):
17
 
55
 
18
     def __init__(self, txt=None):
56
     def __init__(self, txt=None):
104
 
142
 
105
     name = "sardine"
143
     name = "sardine"
106
 
144
 
145
+    cfg_paths = [
146
+        '/etc/sardine/config',
147
+        '%(HOME)s/.config/sardine/config' % os.environ,
148
+        '.sardine.config'
149
+    ]
150
+
151
+    cfg_valid_keys = [
152
+    ]
153
+
107
     def __init__(self, cmdargs):
154
     def __init__(self, cmdargs):
108
         self.cmdargs = cmdargs
155
         self.cmdargs = cmdargs
109
         self._set_pluginpath()
156
         self._set_pluginpath()
157
+        self.config = Config(self.cfg_paths, self.cfg_valid_keys)
110
 
158
 
111
     def _set_pluginpath(self):
159
     def _set_pluginpath(self):
112
         mypath = os.path.dirname(os.path.realpath(sys.argv[0]))
160
         mypath = os.path.dirname(os.path.realpath(sys.argv[0]))