comparison src/tools/config.py @ 1064:7ee9d9db67b9

memory, tools (config): move special config retrieval from memory to tools
author souliane <souliane@mailoo.org>
date Mon, 09 Jun 2014 20:40:13 +0200
parents a5cfa9bb4541
children 9c17bd37e6e5
comparison
equal deleted inserted replaced
1063:6ec513ad92c2 1064:7ee9d9db67b9
24 log = getLogger(__name__) 24 log = getLogger(__name__)
25 25
26 from sat.core.constants import Const as C 26 from sat.core.constants import Const as C
27 from sat.core.i18n import _ 27 from sat.core.i18n import _
28 28
29 from ConfigParser import SafeConfigParser, DEFAULTSECT 29 from ConfigParser import SafeConfigParser, DEFAULTSECT, NoOptionError, NoSectionError
30 from xdg import BaseDirectory 30 from xdg import BaseDirectory
31 import os 31 import os
32 import csv
32 33
33 34
34 def fixConfigOption(section, option, value, silent=True): 35 def fixConfigOption(section, option, value, silent=True):
35 """Force a configuration option value, writing it in the first found user 36 """Force a configuration option value, writing it in the first found user
36 config file, eventually creating a new user config file if none is found. 37 config file, eventually creating a new user config file if none is found.
62 if not silent: 63 if not silent:
63 if option in ('passphrase'): # list here the options storing a password 64 if option in ('passphrase'): # list here the options storing a password
64 value = '******' 65 value = '******'
65 log.warning(_("Config auto-update: %(option)s set to %(value)s in the file %(config_file)s") % 66 log.warning(_("Config auto-update: %(option)s set to %(value)s in the file %(config_file)s") %
66 {'option': option, 'value': value, 'config_file': target_file}) 67 {'option': option, 'value': value, 'config_file': target_file})
68
69
70 def getConfig(config, section, name, default=None):
71 """Get a configuration option
72
73 @param config (SafeConfigParser): the configuration instance
74 @param section (str): section of the config file (None or '' for DEFAULT)
75 @param name (str): name of the option
76 @param default (str): eventually default to this value, if not None
77 @return: str, list or dict
78 """
79 if not section:
80 section = DEFAULTSECT
81
82 try:
83 value = config.get(section, name)
84 except (NoOptionError, NoSectionError) as e:
85 if default is None:
86 raise e
87 value = default
88
89 if name.endswith('_path') or name.endswith('_dir'):
90 value = os.path.expanduser(value)
91 # thx to Brian (http://stackoverflow.com/questions/186857/splitting-a-semicolon-separated-string-to-a-dictionary-in-python/186873#186873)
92 elif name.endswith('_list'):
93 value = csv.reader([value], delimiter=',', quotechar='"').next()
94 elif name.endswith('_dict'):
95 value = dict(csv.reader([item], delimiter=':', quotechar='"').next()
96 for item in csv.reader([value], delimiter=',', quotechar='"').next())
97 return value