wrote basic SimpleConfig docstring
[electrum-nvc.git] / lib / simple_config.py
1 import json, ast
2 import os, ast
3 from util import user_dir, print_error
4
5 from version import ELECTRUM_VERSION, SEED_VERSION
6
7
8
9 class SimpleConfig:
10 """
11
12 The SimpleConfig class is responsible for handling operations involving
13 configuration files.  The constructor reads and stores the system and 
14 user configurations from electrum.conf into seperate dictionaries within
15 a SimpleConfig instance then reads the wallet file.
16
17 """
18     def __init__(self, options={}):
19
20         # system conf, readonly
21         self.system_config = {}
22         self.read_system_config()
23
24         # user conf, writeable
25         self.user_dir = user_dir()
26         self.user_config = {}
27         self.read_user_config()
28
29         # command-line options
30         self.options_config = options
31
32         self.wallet_config = {}
33         self.wallet_file_exists = False
34         self.init_path(self.options_config.get('wallet_path'))
35         print_error( "path", self.path )
36         if self.path:
37             self.read_wallet_config(self.path)
38             
39             
40             
41         
42
43     def set_key(self, key, value, save = False):
44         # find where a setting comes from and save it there
45         if self.options_config.get(key) is not None:
46             print "Warning: not changing '%s' because it was passed as a command-line option"%key
47             return
48
49         elif self.user_config.get(key) is not None:
50             self.user_config[key] = value
51             if save: self.save_user_config()
52
53         elif self.system_config.get(key) is not None:
54             if str(self.system_config[key]) != str(value):
55                 print "Warning: not changing '%s' because it was set in the system configuration"%key
56
57         elif self.wallet_config.get(key) is not None:
58             self.wallet_config[key] = value
59             if save: self.save_wallet_config()
60
61         else:
62             # add key to wallet config
63             self.wallet_config[key] = value
64             if save: self.save_wallet_config()
65
66
67     def get(self, key, default=None):
68         """Retrieve the filepath of the configuration file specified in the 'key' parameter."""
69         # 1. command-line options always override everything
70         if self.options_config.has_key(key) and self.options_config.get(key) is not None:
71             out = self.options_config.get(key)
72
73         # 2. user configuration 
74         elif self.user_config.has_key(key):
75             out = self.user_config.get(key)
76
77         # 2. system configuration
78         elif self.system_config.has_key(key):
79             out = self.system_config.get(key)
80
81         # 3. use the wallet file config
82         else:
83             out = self.wallet_config.get(key)
84
85         if out is None and default is not None:
86             out = default
87
88         # try to fix the type
89         if default is not None and type(out) != type(default):
90             import ast
91             try:
92                 out = ast.literal_eval(out)
93             except TypeError:
94                 print "type error, using default value"
95                 out = default
96
97         return out
98
99
100     def is_modifiable(self, key):
101         if self.options_config.has_key(key):
102             return False
103         elif self.user_config.has_key(key):
104             return True
105         elif self.system_config.has_key(key):
106             return False
107         else:
108             return True
109
110
111     def read_system_config(self):
112         """Parse and store the system config settings in electrum.conf into system_config[]."""
113         name = '/etc/electrum.conf'
114         if os.path.exists(name):
115             try:
116                 import ConfigParser
117             except ImportError:
118                 print "cannot parse electrum.conf. please install ConfigParser"
119                 return
120                 
121             p = ConfigParser.ConfigParser()
122             p.read(name)
123             try:
124                 for k, v in p.items('client'):
125                     self.system_config[k] = v
126             except ConfigParser.NoSectionError:
127                 pass
128
129
130     def read_user_config(self):
131         """Parse and store the user config settings in electrum.conf into user_config[]."""
132         if not self.user_dir: return
133
134         name = os.path.join( self.user_dir, 'electrum.conf')
135         if os.path.exists(name):
136             try:
137                 import ConfigParser
138             except ImportError:
139                 print "cannot parse electrum.conf. please install ConfigParser"
140                 return
141                 
142             p = ConfigParser.ConfigParser()
143             p.read(name)
144             try:
145                 for k, v in p.items('client'):
146                     self.user_config[k] = v
147             except ConfigParser.NoSectionError:
148                 pass
149
150
151     def init_path(self, path):
152         """Set the path of the wallet."""
153
154         if not path:
155             path = self.get('default_wallet_path')
156
157         if path is not None:
158             self.path = path
159             return
160
161         # Look for wallet file in the default data directory.
162         # Make wallet directory if it does not yet exist.
163         if not os.path.exists(self.user_dir):
164             os.mkdir(self.user_dir)
165         self.path = os.path.join(self.user_dir, "electrum.dat")
166
167
168     def save_user_config(self):
169         if not self.user_dir: return
170
171         import ConfigParser
172         config = ConfigParser.RawConfigParser()
173         config.add_section('client')
174         for k,v in self.user_config.items():
175             config.set('client', k, v)
176
177         with open( os.path.join( self.user_dir, 'electrum.conf'), 'wb') as configfile:
178             config.write(configfile)
179         
180
181
182
183     def read_wallet_config(self, path):
184         """Read the contents of the wallet file."""
185         try:
186             with open(self.path, "r") as f:
187                 data = f.read()
188         except IOError:
189             return
190         try:
191             d = ast.literal_eval( data )  #parse raw data from reading wallet file
192         except:
193             raise IOError("Cannot read wallet file.")
194
195         self.wallet_config = d
196         self.wallet_file_exists = True
197
198
199
200     def save(self):
201         self.save_wallet_config()
202
203
204     def save_wallet_config(self):
205         s = repr(self.wallet_config)
206         f = open(self.path,"w")
207         f.write( s )
208         f.close()
209         if self.get('gui') != 'android':
210             import stat
211             os.chmod(self.path,stat.S_IREAD | stat.S_IWRITE)
212