Selaa lähdekoodia

Add basic config mechanism

Alois Mahdal 10 vuotta sitten
vanhempi
commit
9f176b5235
1 muutettua tiedostoa jossa 48 lisäystä ja 0 poistoa
  1. 48
    0
      include/sardine.py

+ 48
- 0
include/sardine.py Näytä tiedosto

@@ -4,6 +4,8 @@ import imp
4 4
 import os
5 5
 import sys
6 6
 
7
+import yaml
8
+
7 9
 
8 10
 class PluginError(Exception):
9 11
     pass
@@ -13,6 +15,42 @@ class PluginUsageError(PluginError):
13 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 54
 class XGPRenderer(object):
17 55
 
18 56
     def __init__(self, txt=None):
@@ -104,9 +142,19 @@ class App:
104 142
 
105 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 154
     def __init__(self, cmdargs):
108 155
         self.cmdargs = cmdargs
109 156
         self._set_pluginpath()
157
+        self.config = Config(self.cfg_paths, self.cfg_valid_keys)
110 158
 
111 159
     def _set_pluginpath(self):
112 160
         mypath = os.path.dirname(os.path.realpath(sys.argv[0]))