Catch the exception if decoding failed.
[pymailheaders.git] / config.py
blob87f87d488318b0617dbf585e40921486b06864d8
1 #!/usr/bin/env python
3 # config.py
4 # Copyright 2007 Neil Shi <zeegeek@gmail.com>
6 # Configuration File Parser
7 # This file contains the configuration parser for pymailheaders
9 # This program is free software; you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 2 of the License, or
12 # (at your option) any later version.
14 # This program is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
19 from ConfigParser import *
20 from sys import stderr
21 import os
22 import os.path
24 class config:
25 """This class parses and saves the configuration file for pymailheaders.
27 @attention: Put all boolean variables names in __bool_vals so that we
28 can return them in the right type later.
30 @note: Private member variables:
31 __section
32 __defaults
33 __bool_vals
34 __int_vals
35 __config_file
36 __config
37 """
39 __section = 'settings'
41 __defaults = {'auth': False,
42 'encrypted': False,
43 'interval': 180,
44 # GUI settings
45 'height': 100,
46 'width': 400,
47 'x': 0,
48 'y': 0,
49 'background': 'black',
50 'foreground': 'green',
51 'foreground new': 'yellow',
52 'font': 'Simsun 12',
53 'border': 0,
54 'decorated': True,
55 'focus': True,
56 'top': False,
57 'pager': True,
58 'taskbar': True,
59 'sticky': False}
61 # boolean options
62 __bool_vals = ('auth',
63 'encrypted',
64 'decorated',
65 'focus',
66 'top',
67 'pager',
68 'taskbar',
69 'sticky')
71 # integer options
72 __int_vals = ('interval',
73 'height',
74 'width',
75 'x',
76 'y',
77 'border')
79 # stores configuration filename
80 __config_file = ''
82 def __init__(self, filename):
83 """Constructor
85 @type filename: string
86 @param filename: full configuration file name
87 """
89 self.__config = SafeConfigParser()
90 self.__config_file = filename
92 try:
93 # if the file does not exist, create it and write
94 # default values to it.
95 if not os.path.isfile(self.__config_file):
96 for k, v in self.__defaults.iteritems():
97 self.set(k, v)
98 self.write()
100 # check if we have the correct permissions
101 fd = open(self.__config_file, 'rw')
102 fd.close()
104 self.__config.read(self.__config_file)
106 # Insert default values
107 # I have to do this because ConfigParser will insert a
108 # section called DEFAULT if I use the defaults method.
109 for k, v in self.__defaults.iteritems():
110 if not self.__has(k): self.set(k, v)
111 except (IOError, ParsingError, MissingSectionHeaderError), strerr:
112 raise Error('config (__init__)', str(strerr))
113 except:
114 raise
116 def __del__(self):
117 """Destructor
119 @note: make sure that changes are being written to the file.
122 self.write()
124 def __has(self, opt):
125 """Determine if an option exists in the config file
127 @type opt: string
128 @param opt: option name
129 @rtype: bool
130 @return: True if it has the option, False otherwise.
133 return self.__config.has_option(self.__section, opt)
135 def set(self, opt, val):
136 """Set option's value to value
138 @type opt: string
139 @param opt: option name
140 @type val: string or bool or int
141 @param val: option's value
144 try:
145 # convert from boolean values
146 if opt in self.__bool_vals:
147 if type(val) != bool:
148 raise TypeError
150 if val:
151 self.__config.set(self.__section, opt, 'yes')
152 else:
153 self.__config.set(self.__section, opt, 'no')
154 # convert from integers
155 elif opt in self.__int_vals:
156 if type(val) != int:
157 raise TypeError
159 self.__config.set(self.__section, opt, str(val))
160 elif type(val) == bool or type(val) == int:
161 raise TypeError
162 else:
163 self.__config.set(self.__section, opt, val)
164 except NoSectionError, strerr:
165 print >> stderr, 'config (set):', strerr
166 print >> stderr, 'config (set): creating...'
168 # create section
169 self.__config.add_section(self.__section)
170 # try to add the option
171 self.set(opt, val)
172 except TypeError:
173 raise Error('config (set)', 'invalid value type')
174 except:
175 raise
177 def get(self, opt):
178 """Get option's value
180 If the option has a boolean value, convert it into boolean type.
181 If it's a integer value, convert it to integer type.
183 @type opt: string
184 @param opt: option name
185 @rtype: string or bool or int
186 @return: option's value
189 try:
190 # convert to boolean values
191 if opt in self.__bool_vals:
192 return self.__config.get(self.__section, opt).lower() == 'yes'
193 # convert to integers
194 elif opt in self.__int_vals:
195 return int(self.__config.get(self.__section, opt))
197 return self.__config.get(self.__section, opt)
198 except (NoSectionError, NoOptionError), strerr:
199 raise Error('config (get)', str(strerr))
201 def get_all(self):
202 """Get all options' values in the right type
204 @rtype: dictionary
205 @return: options' values
208 optvals = {}
210 try:
211 opts = self.__config.options(self.__section)
213 for k in opts:
214 optvals[k] = self.get(k)
215 except:
216 raise
218 return optvals
220 def write(self):
221 """Write configurations to file
224 try:
225 # make sure that all options will be written into the
226 # config file
227 for k, v in self.__defaults.iteritems():
228 if not self.__has(k): self.set(k, v)
230 fd = open(self.__config_file, 'w')
232 self.__config.write(fd)
234 fd.close()
236 # Set file permission bits to 0600
237 os.chmod(self.__config_file, 0600)
239 except IOError, strerr:
240 raise Error('config (write)', str(strerr))