1 """ wrapper for ini-file-based settings"""
7 """ Reads and writes settings to a config files based on the INI format.
9 For example, a typical mEveMon config file (at '~/.mevemon/mevemon.cfg')will look like this:
14 ver_code = <ver_code1>
18 ver_code = <ver_code2>
21 # this is just a fake example, we don't store any general
23 super_cow_powers = True
25 More information on the format/syntax of the config file can be found
26 on the ConfigObj site (http://www.voidspace.org.uk/python/configobj.html#the-config-file-format).
28 def __init__(self, cfg_file=constants.CONFIG_PATH):
29 self.cfg_file = cfg_file
30 self._convert_gconf_to_cfgfile()
31 self._detect_and_backup_old_cfg()
32 self.config = configobj.ConfigObj(self.cfg_file)
34 def get_accounts(self):
35 """ Returns a dictionary containing key_id:ver_code pairs gathered from the config file
39 cfg_accounts = self.config['accounts'].values()
43 for account in cfg_accounts:
44 account_dict[account['key_id']] = account['ver_code']
48 def get_ver_code(self, key_id):
49 """ Returns the verification code associated with the given key_id.
52 ver_code = self.get_accounts()[key_id]
55 raise Exception("KEY_ID '%s' is not in settings")
57 def add_account(self, key_id, ver_code):
58 """ Adds the provided key_id:ver_code pair to the config file.
60 if 'accounts' not in self.config.sections:
61 self.config['accounts'] = {}
63 self.config['accounts']['account.%s' % key_id] = {}
64 self.config['accounts']['account.%s' % key_id]['key_id'] = key_id
65 self.config['accounts']['account.%s' % key_id]['ver_code'] = ver_code
68 def remove_account(self, key_id):
69 """ Removes the provided key_id key from the config file
71 for key in self.config['accounts']:
72 if self.config['accounts'][key]['key_id'] == key_id:
73 del self.config['accounts'][key]
77 """ write out the settings into the config file """
78 if isinstance(self.cfg_file, str):
80 else: # cfg_file is a file-like object (StringIO, etc..)
81 self.config.write(self.cfg_file)
83 def _convert_gconf_to_cfgfile(self):
84 """ A temporary method to convert from the old 0.4-9 gconf-based
85 settings to the new file-based settings.
88 gsettings = gconf_settings.Settings()
89 for key_id, ver_code in gsettings.get_accounts().items():
90 self.add_account(key_id, ver_code)
91 gsettings.remove_account(key_id)
93 def _detect_and_backup_old_cfg(self):
94 """ Searches the config file for the string 'apikey', which
95 would only be present in the old legacy config file. If it's
96 found, it backs up the file and we start over.
99 temp = open(self.cfg_file, "r")
101 # if it's not here, forget about it - mission accomplished
103 config_contents = temp.read()
105 if config_contents.find('apikey') > 0:
106 # move the file then create a new one
107 os.rename(self.cfg_file, self.cfg_file + '.old')
109 # we've got an updated cfg file